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.

Table.java 63KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935
  1. /*
  2. Copyright (c) 2005 Health Market Science, Inc.
  3. This library is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU Lesser General Public
  5. License as published by the Free Software Foundation; either
  6. version 2.1 of the License, or (at your option) any later version.
  7. This library is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  10. Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public
  12. License along with this library; if not, write to the Free Software
  13. Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
  14. USA
  15. You can contact Health Market Science at info@healthmarketscience.com
  16. or at the following address:
  17. Health Market Science
  18. 2700 Horizon Drive
  19. Suite 200
  20. King of Prussia, PA 19406
  21. */
  22. package com.healthmarketscience.jackcess;
  23. import java.io.IOException;
  24. import java.nio.ByteBuffer;
  25. import java.util.ArrayList;
  26. import java.util.Arrays;
  27. import java.util.Collection;
  28. import java.util.Collections;
  29. import java.util.Comparator;
  30. import java.util.Iterator;
  31. import java.util.LinkedHashMap;
  32. import java.util.List;
  33. import java.util.Map;
  34. import org.apache.commons.logging.Log;
  35. import org.apache.commons.logging.LogFactory;
  36. /**
  37. * A single database table
  38. * <p>
  39. * Is not thread-safe.
  40. *
  41. * @author Tim McCune
  42. */
  43. public class Table
  44. implements Iterable<Map<String, Object>>
  45. {
  46. private static final Log LOG = LogFactory.getLog(Table.class);
  47. private static final short OFFSET_MASK = (short)0x1FFF;
  48. private static final short DELETED_ROW_MASK = (short)0x8000;
  49. private static final short OVERFLOW_ROW_MASK = (short)0x4000;
  50. /** Table type code for system tables */
  51. public static final byte TYPE_SYSTEM = 0x53;
  52. /** Table type code for user tables */
  53. public static final byte TYPE_USER = 0x4e;
  54. /** comparator which sorts variable length columns vased on their index into
  55. the variable length offset table */
  56. private static final Comparator<Column> VAR_LEN_COLUMN_COMPARATOR =
  57. new Comparator<Column>() {
  58. public int compare(Column c1, Column c2) {
  59. return ((c1.getVarLenTableIndex() < c2.getVarLenTableIndex()) ? -1 :
  60. ((c1.getVarLenTableIndex() > c2.getVarLenTableIndex()) ? 1 :
  61. 0));
  62. }
  63. };
  64. /** owning database */
  65. private final Database _database;
  66. /** Type of the table (either TYPE_SYSTEM or TYPE_USER) */
  67. private byte _tableType;
  68. /** Number of indexes on the table */
  69. private int _indexCount;
  70. /** Number of index slots for the table */
  71. private int _indexSlotCount;
  72. /** Number of rows in the table */
  73. private int _rowCount;
  74. /** last auto number for the table */
  75. private int _lastAutoNumber;
  76. /** page number of the definition of this table */
  77. private final int _tableDefPageNumber;
  78. /** max Number of columns in the table (includes previous deletions) */
  79. private short _maxColumnCount;
  80. /** max Number of variable columns in the table */
  81. private short _maxVarColumnCount;
  82. /** List of columns in this table, ordered by column number */
  83. private List<Column> _columns = new ArrayList<Column>();
  84. /** List of variable length columns in this table, ordered by offset */
  85. private List<Column> _varColumns = new ArrayList<Column>();
  86. /** List of indexes on this table */
  87. private List<Index> _indexes = new ArrayList<Index>();
  88. /** Table name as stored in Database */
  89. private final String _name;
  90. /** Usage map of pages that this table owns */
  91. private UsageMap _ownedPages;
  92. /** Usage map of pages that this table owns with free space on them */
  93. private UsageMap _freeSpacePages;
  94. /** modification count for the table, keeps row-states up-to-date */
  95. private int _modCount;
  96. /** page buffer used to update data pages when adding rows */
  97. private final TempPageHolder _addRowBufferH =
  98. TempPageHolder.newHolder(TempBufferHolder.Type.SOFT);
  99. /** page buffer used to update the table def page */
  100. private final TempPageHolder _tableDefBufferH =
  101. TempPageHolder.newHolder(TempBufferHolder.Type.SOFT);
  102. /** buffer used to writing single rows of data */
  103. private final TempBufferHolder _singleRowBufferH =
  104. TempBufferHolder.newHolder(TempBufferHolder.Type.SOFT, true);
  105. /** "buffer" used to writing multi rows of data (will create new buffer on
  106. every call) */
  107. private final TempBufferHolder _multiRowBufferH =
  108. TempBufferHolder.newHolder(TempBufferHolder.Type.NONE, true);
  109. /** page buffer used to write out-of-line "long value" data */
  110. private final TempPageHolder _longValueBufferH =
  111. TempPageHolder.newHolder(TempBufferHolder.Type.SOFT);
  112. /** for now, "big index support" is optional */
  113. private final boolean _useBigIndex;
  114. /** optional error handler to use when row errors are encountered */
  115. private ErrorHandler _tableErrorHandler;
  116. /** common cursor for iterating through the table, kept here for historic
  117. reasons */
  118. private Cursor _cursor;
  119. /**
  120. * Only used by unit tests
  121. */
  122. Table(boolean testing, List<Column> columns) throws IOException {
  123. if(!testing) {
  124. throw new IllegalArgumentException();
  125. }
  126. _database = null;
  127. _tableDefPageNumber = PageChannel.INVALID_PAGE_NUMBER;
  128. _name = null;
  129. _useBigIndex = false;
  130. setColumns(columns);
  131. }
  132. /**
  133. * @param database database which owns this table
  134. * @param tableBuffer Buffer to read the table with
  135. * @param pageNumber Page number of the table definition
  136. * @param name Table name
  137. * @param useBigIndex whether or not "big index support" should be enabled
  138. * for the table
  139. */
  140. protected Table(Database database, ByteBuffer tableBuffer,
  141. int pageNumber, String name, boolean useBigIndex)
  142. throws IOException
  143. {
  144. _database = database;
  145. _tableDefPageNumber = pageNumber;
  146. _name = name;
  147. _useBigIndex = useBigIndex;
  148. int nextPage = tableBuffer.getInt(getFormat().OFFSET_NEXT_TABLE_DEF_PAGE);
  149. ByteBuffer nextPageBuffer = null;
  150. while (nextPage != 0) {
  151. if (nextPageBuffer == null) {
  152. nextPageBuffer = getPageChannel().createPageBuffer();
  153. }
  154. getPageChannel().readPage(nextPageBuffer, nextPage);
  155. nextPage = nextPageBuffer.getInt(getFormat().OFFSET_NEXT_TABLE_DEF_PAGE);
  156. ByteBuffer newBuffer = getPageChannel().createBuffer(
  157. tableBuffer.capacity() + getFormat().PAGE_SIZE - 8);
  158. newBuffer.put(tableBuffer);
  159. newBuffer.put(nextPageBuffer.array(), 8, getFormat().PAGE_SIZE - 8);
  160. tableBuffer = newBuffer;
  161. tableBuffer.flip();
  162. }
  163. readTableDefinition(tableBuffer);
  164. tableBuffer = null;
  165. // setup common cursor
  166. _cursor = Cursor.createCursor(this);
  167. }
  168. /**
  169. * @return The name of the table
  170. */
  171. public String getName() {
  172. return _name;
  173. }
  174. public boolean doUseBigIndex() {
  175. return _useBigIndex;
  176. }
  177. public int getMaxColumnCount() {
  178. return _maxColumnCount;
  179. }
  180. public int getColumnCount() {
  181. return _columns.size();
  182. }
  183. public Database getDatabase() {
  184. return _database;
  185. }
  186. public JetFormat getFormat() {
  187. return getDatabase().getFormat();
  188. }
  189. public PageChannel getPageChannel() {
  190. return getDatabase().getPageChannel();
  191. }
  192. /**
  193. * Gets the currently configured ErrorHandler (always non-{@code null}).
  194. * This will be used to handle all errors unless overridden at the Cursor
  195. * level.
  196. */
  197. public ErrorHandler getErrorHandler() {
  198. return((_tableErrorHandler != null) ? _tableErrorHandler :
  199. getDatabase().getErrorHandler());
  200. }
  201. /**
  202. * Sets a new ErrorHandler. If {@code null}, resets to using the
  203. * ErrorHandler configured at the Database level.
  204. */
  205. public void setErrorHandler(ErrorHandler newErrorHandler) {
  206. _tableErrorHandler = newErrorHandler;
  207. }
  208. protected int getTableDefPageNumber() {
  209. return _tableDefPageNumber;
  210. }
  211. public RowState createRowState() {
  212. return new RowState(TempBufferHolder.Type.HARD);
  213. }
  214. protected UsageMap.PageCursor getOwnedPagesCursor() {
  215. return _ownedPages.cursor();
  216. }
  217. protected TempPageHolder getLongValueBuffer() {
  218. return _longValueBufferH;
  219. }
  220. /**
  221. * @return All of the columns in this table (unmodifiable List)
  222. */
  223. public List<Column> getColumns() {
  224. return Collections.unmodifiableList(_columns);
  225. }
  226. /**
  227. * @return the column with the given name
  228. */
  229. public Column getColumn(String name) {
  230. for(Column column : _columns) {
  231. if(column.getName().equals(name)) {
  232. return column;
  233. }
  234. }
  235. throw new IllegalArgumentException("Column with name " + name +
  236. " does not exist in this table");
  237. }
  238. /**
  239. * Only called by unit tests
  240. */
  241. private void setColumns(List<Column> columns) {
  242. _columns = columns;
  243. int colIdx = 0;
  244. int varLenIdx = 0;
  245. int fixedOffset = 0;
  246. for(Column col : _columns) {
  247. col.setColumnNumber((short)colIdx);
  248. col.setColumnIndex(colIdx++);
  249. if(col.isVariableLength()) {
  250. col.setVarLenTableIndex(varLenIdx++);
  251. _varColumns.add(col);
  252. } else {
  253. col.setFixedDataOffset(fixedOffset);
  254. fixedOffset += col.getType().getFixedSize();
  255. }
  256. }
  257. _maxColumnCount = (short)_columns.size();
  258. _maxVarColumnCount = (short)_varColumns.size();
  259. }
  260. /**
  261. * @return All of the Indexes on this table (unmodifiable List)
  262. */
  263. public List<Index> getIndexes() {
  264. return Collections.unmodifiableList(_indexes);
  265. }
  266. /**
  267. * @return the index with the given name
  268. */
  269. public Index getIndex(String name) {
  270. for(Index index : _indexes) {
  271. if(index.getName().equals(name)) {
  272. return index;
  273. }
  274. }
  275. throw new IllegalArgumentException("Index with name " + name +
  276. " does not exist on this table");
  277. }
  278. /**
  279. * Only called by unit tests
  280. */
  281. int getIndexSlotCount() {
  282. return _indexSlotCount;
  283. }
  284. /**
  285. * After calling this method, getNextRow will return the first row in the
  286. * table
  287. */
  288. public void reset() {
  289. _cursor.reset();
  290. }
  291. /**
  292. * Delete the current row (retrieved by a call to {@link #getNextRow()}).
  293. */
  294. public void deleteCurrentRow() throws IOException {
  295. _cursor.deleteCurrentRow();
  296. }
  297. /**
  298. * Delete the row on which the given rowState is currently positioned.
  299. */
  300. public void deleteRow(RowState rowState, RowId rowId) throws IOException {
  301. requireValidRowId(rowId);
  302. // ensure that the relevant row state is up-to-date
  303. ByteBuffer rowBuffer = positionAtRowHeader(rowState, rowId);
  304. requireNonDeletedRow(rowState, rowId);
  305. // delete flag always gets set in the "header" row (even if data is on
  306. // overflow row)
  307. int pageNumber = rowState.getHeaderRowId().getPageNumber();
  308. int rowNumber = rowState.getHeaderRowId().getRowNumber();
  309. // use any read rowValues to help update the indexes
  310. Object[] rowValues = (!_indexes.isEmpty() ?
  311. rowState.getRowValues() : null);
  312. int rowIndex = getRowStartOffset(rowNumber, getFormat());
  313. rowBuffer.putShort(rowIndex, (short)(rowBuffer.getShort(rowIndex)
  314. | DELETED_ROW_MASK | OVERFLOW_ROW_MASK));
  315. writeDataPage(rowBuffer, pageNumber);
  316. // update the indexes
  317. for(Index index : _indexes) {
  318. index.deleteRow(rowValues, rowId);
  319. }
  320. // make sure table def gets updated
  321. updateTableDefinition(-1);
  322. }
  323. /**
  324. * @return The next row in this table (Column name -> Column value)
  325. */
  326. public Map<String, Object> getNextRow() throws IOException {
  327. return getNextRow(null);
  328. }
  329. /**
  330. * @param columnNames Only column names in this collection will be returned
  331. * @return The next row in this table (Column name -> Column value)
  332. */
  333. public Map<String, Object> getNextRow(Collection<String> columnNames)
  334. throws IOException
  335. {
  336. return _cursor.getNextRow(columnNames);
  337. }
  338. /**
  339. * Reads a single column from the given row.
  340. */
  341. public Object getRowValue(RowState rowState, RowId rowId, Column column)
  342. throws IOException
  343. {
  344. if(this != column.getTable()) {
  345. throw new IllegalArgumentException(
  346. "Given column " + column + " is not from this table");
  347. }
  348. requireValidRowId(rowId);
  349. // position at correct row
  350. ByteBuffer rowBuffer = positionAtRowData(rowState, rowId);
  351. requireNonDeletedRow(rowState, rowId);
  352. Object value = getRowColumn(rowBuffer, getRowNullMask(rowBuffer), column,
  353. rowState);
  354. // cache the row values in order to be able to update the index on row
  355. // deletion. note, most of the returned values are immutable, except
  356. // for binary data (returned as byte[]), but binary data shouldn't be
  357. // indexed anyway.
  358. rowState.setRowValue(column.getColumnIndex(), value);
  359. return value;
  360. }
  361. /**
  362. * Reads some columns from the given row.
  363. * @param columnNames Only column names in this collection will be returned
  364. */
  365. public Map<String, Object> getRow(
  366. RowState rowState, RowId rowId, Collection<String> columnNames)
  367. throws IOException
  368. {
  369. requireValidRowId(rowId);
  370. // position at correct row
  371. ByteBuffer rowBuffer = positionAtRowData(rowState, rowId);
  372. requireNonDeletedRow(rowState, rowId);
  373. return getRow(rowState, rowBuffer, getRowNullMask(rowBuffer), _columns,
  374. columnNames);
  375. }
  376. /**
  377. * Reads the row data from the given row buffer. Leaves limit unchanged.
  378. * Saves parsed row values to the given rowState.
  379. */
  380. private static Map<String, Object> getRow(
  381. RowState rowState,
  382. ByteBuffer rowBuffer,
  383. NullMask nullMask,
  384. Collection<Column> columns,
  385. Collection<String> columnNames)
  386. throws IOException
  387. {
  388. Map<String, Object> rtn = new LinkedHashMap<String, Object>(
  389. columns.size());
  390. for(Column column : columns) {
  391. if((columnNames == null) || (columnNames.contains(column.getName()))) {
  392. // Add the value to the row data
  393. Object value = getRowColumn(rowBuffer, nullMask, column, rowState);
  394. rtn.put(column.getName(), value);
  395. // cache the row values in order to be able to update the index on row
  396. // deletion. note, most of the returned values are immutable, except
  397. // for binary data (returned as byte[]), but binary data shouldn't be
  398. // indexed anyway.
  399. rowState.setRowValue(column.getColumnIndex(), value);
  400. }
  401. }
  402. return rtn;
  403. }
  404. /**
  405. * Reads the column data from the given row buffer. Leaves limit unchanged.
  406. */
  407. private static Object getRowColumn(ByteBuffer rowBuffer,
  408. NullMask nullMask,
  409. Column column,
  410. RowState rowState)
  411. throws IOException
  412. {
  413. byte[] columnData = null;
  414. try {
  415. boolean isNull = nullMask.isNull(column);
  416. if(column.getType() == DataType.BOOLEAN) {
  417. return Boolean.valueOf(!isNull); //Boolean values are stored in the null mask
  418. } else if(isNull) {
  419. // well, that's easy!
  420. return null;
  421. }
  422. // reset position to row start
  423. rowBuffer.reset();
  424. // locate the column data bytes
  425. int rowStart = rowBuffer.position();
  426. int colDataPos = 0;
  427. int colDataLen = 0;
  428. if(!column.isVariableLength()) {
  429. // read fixed length value (non-boolean at this point)
  430. int dataStart = rowStart + 2;
  431. colDataPos = dataStart + column.getFixedDataOffset();
  432. colDataLen = column.getType().getFixedSize();
  433. } else {
  434. // read var length value
  435. int varColumnOffsetPos =
  436. (rowBuffer.limit() - nullMask.byteSize() - 4) -
  437. (column.getVarLenTableIndex() * 2);
  438. short varDataStart = rowBuffer.getShort(varColumnOffsetPos);
  439. short varDataEnd = rowBuffer.getShort(varColumnOffsetPos - 2);
  440. colDataPos = rowStart + varDataStart;
  441. colDataLen = varDataEnd - varDataStart;
  442. }
  443. // grab the column data
  444. columnData = new byte[colDataLen];
  445. rowBuffer.position(colDataPos);
  446. rowBuffer.get(columnData);
  447. // parse the column data
  448. return column.read(columnData);
  449. } catch(Exception e) {
  450. return rowState.handleRowError(column, columnData, e);
  451. }
  452. }
  453. /**
  454. * Reads the null mask from the given row buffer. Leaves limit unchanged.
  455. */
  456. private static NullMask getRowNullMask(ByteBuffer rowBuffer)
  457. throws IOException
  458. {
  459. // reset position to row start
  460. rowBuffer.reset();
  461. short columnCount = rowBuffer.getShort(); // Number of columns in this row
  462. // read null mask
  463. NullMask nullMask = new NullMask(columnCount);
  464. rowBuffer.position(rowBuffer.limit() - nullMask.byteSize()); //Null mask at end
  465. nullMask.read(rowBuffer);
  466. return nullMask;
  467. }
  468. /**
  469. * Sets a new buffer to the correct row header page using the given rowState
  470. * according to the given rowId. Deleted state is
  471. * determined, but overflow row pointers are not followed.
  472. *
  473. * @return a ByteBuffer of the relevant page, or null if row was invalid
  474. */
  475. public static ByteBuffer positionAtRowHeader(RowState rowState,
  476. RowId rowId)
  477. throws IOException
  478. {
  479. ByteBuffer rowBuffer = rowState.setHeaderRow(rowId);
  480. if(rowState.isAtHeaderRow()) {
  481. // this task has already been accomplished
  482. return rowBuffer;
  483. }
  484. if(!rowState.isValid()) {
  485. // this was an invalid page/row
  486. rowState.setStatus(RowStateStatus.AT_HEADER);
  487. return null;
  488. }
  489. // note, we don't use findRowStart here cause we need the unmasked value
  490. short rowStart = rowBuffer.getShort(
  491. getRowStartOffset(rowId.getRowNumber(),
  492. rowState.getTable().getFormat()));
  493. // check the deleted, overflow flags for the row (the "real" flags are
  494. // always set on the header row)
  495. RowStatus rowStatus = RowStatus.NORMAL;
  496. if(isDeletedRow(rowStart)) {
  497. rowStatus = RowStatus.DELETED;
  498. } else if(isOverflowRow(rowStart)) {
  499. rowStatus = RowStatus.OVERFLOW;
  500. }
  501. rowState.setRowStatus(rowStatus);
  502. rowState.setStatus(RowStateStatus.AT_HEADER);
  503. return rowBuffer;
  504. }
  505. /**
  506. * Sets the position and limit in a new buffer using the given rowState
  507. * according to the given row number and row end, following overflow row
  508. * pointers as necessary.
  509. *
  510. * @return a ByteBuffer narrowed to the actual row data, or null if row was
  511. * invalid or deleted
  512. */
  513. public static ByteBuffer positionAtRowData(RowState rowState,
  514. RowId rowId)
  515. throws IOException
  516. {
  517. positionAtRowHeader(rowState, rowId);
  518. if(!rowState.isValid() || rowState.isDeleted()) {
  519. // row is invalid or deleted
  520. rowState.setStatus(RowStateStatus.AT_FINAL);
  521. return null;
  522. }
  523. ByteBuffer rowBuffer = rowState.getFinalPage();
  524. int rowNum = rowState.getFinalRowId().getRowNumber();
  525. JetFormat format = rowState.getTable().getFormat();
  526. if(rowState.isAtFinalRow()) {
  527. // we've already found the final row data
  528. return PageChannel.narrowBuffer(
  529. rowBuffer,
  530. findRowStart(rowBuffer, rowNum, format),
  531. findRowEnd(rowBuffer, rowNum, format));
  532. }
  533. while(true) {
  534. // note, we don't use findRowStart here cause we need the unmasked value
  535. short rowStart = rowBuffer.getShort(getRowStartOffset(rowNum, format));
  536. short rowEnd = findRowEnd(rowBuffer, rowNum, format);
  537. // note, at this point we know the row is not deleted, so ignore any
  538. // subsequent deleted flags (as overflow rows are always marked deleted
  539. // anyway)
  540. boolean overflowRow = isOverflowRow(rowStart);
  541. // now, strip flags from rowStart offset
  542. rowStart = (short)(rowStart & OFFSET_MASK);
  543. if (overflowRow) {
  544. if((rowEnd - rowStart) < 4) {
  545. throw new IOException("invalid overflow row info");
  546. }
  547. // Overflow page. the "row" data in the current page points to
  548. // another page/row
  549. int overflowRowNum = ByteUtil.getUnsignedByte(rowBuffer, rowStart);
  550. int overflowPageNum = ByteUtil.get3ByteInt(rowBuffer, rowStart + 1);
  551. rowBuffer = rowState.setOverflowRow(
  552. new RowId(overflowPageNum, overflowRowNum));
  553. rowNum = overflowRowNum;
  554. } else {
  555. rowState.setStatus(RowStateStatus.AT_FINAL);
  556. return PageChannel.narrowBuffer(rowBuffer, rowStart, rowEnd);
  557. }
  558. }
  559. }
  560. /**
  561. * Calls <code>reset</code> on this table and returns an unmodifiable
  562. * Iterator which will iterate through all the rows of this table. Use of
  563. * the Iterator follows the same restrictions as a call to
  564. * <code>getNextRow</code>.
  565. * @throws IllegalStateException if an IOException is thrown by one of the
  566. * operations, the actual exception will be contained within
  567. */
  568. public Iterator<Map<String, Object>> iterator()
  569. {
  570. return iterator(null);
  571. }
  572. /**
  573. * Calls <code>reset</code> on this table and returns an unmodifiable
  574. * Iterator which will iterate through all the rows of this table, returning
  575. * only the given columns. Use of the Iterator follows the same
  576. * restrictions as a call to <code>getNextRow</code>.
  577. * @throws IllegalStateException if an IOException is thrown by one of the
  578. * operations, the actual exception will be contained within
  579. */
  580. public Iterator<Map<String, Object>> iterator(Collection<String> columnNames)
  581. {
  582. reset();
  583. return _cursor.iterator(columnNames);
  584. }
  585. /**
  586. * Writes a new table defined by the given columns to the database.
  587. * @return the first page of the new table's definition
  588. */
  589. public static int writeTableDefinition(
  590. List<Column> columns, PageChannel pageChannel, JetFormat format)
  591. throws IOException
  592. {
  593. // first, create the usage map page
  594. int usageMapPageNumber = pageChannel.writeNewPage(
  595. createUsageMapDefinitionBuffer(pageChannel, format));
  596. // next, determine how big the table def will be (in case it will be more
  597. // than one page)
  598. int totalTableDefSize = format.SIZE_TDEF_HEADER +
  599. (format.SIZE_COLUMN_DEF_BLOCK * columns.size()) +
  600. format.SIZE_TDEF_TRAILER;
  601. for(Column col : columns) {
  602. // we add the number of bytes for the column name and 2 bytes for the
  603. // length of the column name
  604. int nameByteLen = (col.getName().length() *
  605. JetFormat.TEXT_FIELD_UNIT_SIZE);
  606. totalTableDefSize += nameByteLen + 2;
  607. }
  608. // now, create the table definition
  609. ByteBuffer buffer = pageChannel.createBuffer(Math.max(totalTableDefSize,
  610. format.PAGE_SIZE));
  611. writeTableDefinitionHeader(buffer, columns, usageMapPageNumber,
  612. totalTableDefSize, format);
  613. writeColumnDefinitions(buffer, columns, format);
  614. //End of tabledef
  615. buffer.put((byte) 0xff);
  616. buffer.put((byte) 0xff);
  617. // write table buffer to database
  618. int tdefPageNumber = PageChannel.INVALID_PAGE_NUMBER;
  619. if(totalTableDefSize <= format.PAGE_SIZE) {
  620. // easy case, fits on one page
  621. buffer.putShort(format.OFFSET_FREE_SPACE,
  622. (short)(buffer.remaining() - 8)); // overwrite page free space
  623. // Write the tdef page to disk.
  624. tdefPageNumber = pageChannel.writeNewPage(buffer);
  625. } else {
  626. // need to split across multiple pages
  627. ByteBuffer partialTdef = pageChannel.createPageBuffer();
  628. buffer.rewind();
  629. int nextTdefPageNumber = PageChannel.INVALID_PAGE_NUMBER;
  630. while(buffer.hasRemaining()) {
  631. // reset for next write
  632. partialTdef.clear();
  633. if(tdefPageNumber == PageChannel.INVALID_PAGE_NUMBER) {
  634. // this is the first page. note, the first page already has the
  635. // page header, so no need to write it here
  636. tdefPageNumber = pageChannel.allocateNewPage();
  637. nextTdefPageNumber = tdefPageNumber;
  638. } else {
  639. // write page header
  640. writeTablePageHeader(partialTdef);
  641. }
  642. // copy the next page of tdef bytes
  643. int curTdefPageNumber = nextTdefPageNumber;
  644. int writeLen = Math.min(partialTdef.remaining(), buffer.remaining());
  645. partialTdef.put(buffer.array(), buffer.position(), writeLen);
  646. buffer.position(buffer.position() + writeLen);
  647. if(buffer.hasRemaining()) {
  648. // need a next page
  649. nextTdefPageNumber = pageChannel.allocateNewPage();
  650. partialTdef.putInt(format.OFFSET_NEXT_TABLE_DEF_PAGE,
  651. nextTdefPageNumber);
  652. }
  653. // update page free space
  654. partialTdef.putShort(format.OFFSET_FREE_SPACE,
  655. (short)(partialTdef.remaining() - 8)); // overwrite page free space
  656. // write partial page to disk
  657. pageChannel.writePage(partialTdef, curTdefPageNumber);
  658. }
  659. }
  660. return tdefPageNumber;
  661. }
  662. /**
  663. * @param buffer Buffer to write to
  664. * @param columns List of Columns in the table
  665. */
  666. private static void writeTableDefinitionHeader(
  667. ByteBuffer buffer, List<Column> columns,
  668. int usageMapPageNumber, int totalTableDefSize, JetFormat format)
  669. throws IOException
  670. {
  671. //Start writing the tdef
  672. writeTablePageHeader(buffer);
  673. buffer.putInt(totalTableDefSize); //Length of table def
  674. buffer.put((byte) 0x59); //Unknown
  675. buffer.put((byte) 0x06); //Unknown
  676. buffer.putShort((short) 0); //Unknown
  677. buffer.putInt(0); //Number of rows
  678. buffer.putInt(0); //Last Autonumber
  679. if(countAutoNumberColumns(columns) > 0) {
  680. buffer.put((byte) 1);
  681. } else {
  682. buffer.put((byte) 0);
  683. }
  684. for (int i = 0; i < 15; i++) { //Unknown
  685. buffer.put((byte) 0);
  686. }
  687. buffer.put(Table.TYPE_USER); //Table type
  688. buffer.putShort((short) columns.size()); //Max columns a row will have
  689. buffer.putShort(Column.countVariableLength(columns)); //Number of variable columns in table
  690. buffer.putShort((short) columns.size()); //Number of columns in table
  691. buffer.putInt(0); //Number of indexes in table
  692. buffer.putInt(0); //Number of indexes in table
  693. buffer.put((byte) 0); //Usage map row number
  694. ByteUtil.put3ByteInt(buffer, usageMapPageNumber); //Usage map page number
  695. buffer.put((byte) 1); //Free map row number
  696. ByteUtil.put3ByteInt(buffer, usageMapPageNumber); //Free map page number
  697. if (LOG.isDebugEnabled()) {
  698. int position = buffer.position();
  699. buffer.rewind();
  700. LOG.debug("Creating new table def block:\n" + ByteUtil.toHexString(
  701. buffer, format.SIZE_TDEF_HEADER));
  702. buffer.position(position);
  703. }
  704. }
  705. /**
  706. * Writes the page header for a table definition page
  707. * @param buffer Buffer to write to
  708. */
  709. private static void writeTablePageHeader(ByteBuffer buffer)
  710. {
  711. buffer.put(PageTypes.TABLE_DEF); //Page type
  712. buffer.put((byte) 0x01); //Unknown
  713. buffer.put((byte) 0); //Unknown
  714. buffer.put((byte) 0); //Unknown
  715. buffer.putInt(0); //Next TDEF page pointer
  716. }
  717. /**
  718. * @param buffer Buffer to write to
  719. * @param columns List of Columns to write definitions for
  720. */
  721. private static void writeColumnDefinitions(
  722. ByteBuffer buffer, List<Column> columns, JetFormat format)
  723. throws IOException
  724. {
  725. short columnNumber = (short) 0;
  726. short fixedOffset = (short) 0;
  727. short variableOffset = (short) 0;
  728. // we specifically put the "long variable" values after the normal
  729. // variable length values so that we have a better chance of fitting it
  730. // all (because "long variable" values can go in separate pages)
  731. short longVariableOffset =
  732. Column.countNonLongVariableLength(columns);
  733. for (Column col : columns) {
  734. int position = buffer.position();
  735. buffer.put(col.getType().getValue());
  736. buffer.put((byte) 0x59); //Unknown
  737. buffer.put((byte) 0x06); //Unknown
  738. buffer.putShort((short) 0); //Unknown
  739. buffer.putShort(columnNumber); //Column Number
  740. if (col.isVariableLength()) {
  741. if(!col.getType().isLongValue()) {
  742. buffer.putShort(variableOffset++);
  743. } else {
  744. buffer.putShort(longVariableOffset++);
  745. }
  746. } else {
  747. buffer.putShort((short) 0);
  748. }
  749. buffer.putShort(columnNumber); //Column Number again
  750. if(col.getType().getHasScalePrecision()) {
  751. buffer.put(col.getPrecision()); // numeric precision
  752. buffer.put(col.getScale()); // numeric scale
  753. } else {
  754. buffer.put((byte) 0x00); //unused
  755. buffer.put((byte) 0x00); //unused
  756. }
  757. buffer.putShort((short) 0); //Unknown
  758. buffer.put(getColumnBitFlags(col)); // misc col flags
  759. if (col.isCompressedUnicode()) { //Compressed
  760. buffer.put((byte) 1);
  761. } else {
  762. buffer.put((byte) 0);
  763. }
  764. buffer.putInt(0); //Unknown, but always 0.
  765. //Offset for fixed length columns
  766. if (col.isVariableLength()) {
  767. buffer.putShort((short) 0);
  768. } else {
  769. buffer.putShort(fixedOffset);
  770. fixedOffset += col.getType().getFixedSize();
  771. }
  772. if(!col.getType().isLongValue()) {
  773. buffer.putShort(col.getLength()); //Column length
  774. } else {
  775. buffer.putShort((short)0x0000); // unused
  776. }
  777. columnNumber++;
  778. if (LOG.isDebugEnabled()) {
  779. LOG.debug("Creating new column def block\n" + ByteUtil.toHexString(
  780. buffer, position, format.SIZE_COLUMN_DEF_BLOCK));
  781. }
  782. }
  783. for (Column col : columns) {
  784. writeName(buffer, col.getName(), format);
  785. }
  786. }
  787. /**
  788. * Writes the given name into the given buffer in the format as expected by
  789. * {@link #readName}.
  790. */
  791. private static void writeName(ByteBuffer buffer, String name,
  792. JetFormat format)
  793. {
  794. ByteBuffer encName = Column.encodeUncompressedText(
  795. name, format);
  796. buffer.putShort((short) encName.remaining());
  797. buffer.put(encName);
  798. }
  799. /**
  800. * Constructs a byte containing the flags for the given column.
  801. */
  802. private static byte getColumnBitFlags(Column col) {
  803. byte flags = Column.UNKNOWN_FLAG_MASK;
  804. if(!col.isVariableLength()) {
  805. flags |= Column.FIXED_LEN_FLAG_MASK;
  806. }
  807. if(col.isAutoNumber()) {
  808. flags |= Column.AUTO_NUMBER_FLAG_MASK;
  809. }
  810. return flags;
  811. }
  812. /**
  813. * Create the usage map definition page buffer. The "used pages" map is in
  814. * row 0, the "pages with free space" map is in row 1.
  815. */
  816. private static ByteBuffer createUsageMapDefinitionBuffer(
  817. PageChannel pageChannel, JetFormat format)
  818. throws IOException
  819. {
  820. int usageMapRowLength = format.OFFSET_USAGE_MAP_START +
  821. format.USAGE_MAP_TABLE_BYTE_LENGTH;
  822. int freeSpace = format.PAGE_INITIAL_FREE_SPACE
  823. - (2 * getRowSpaceUsage(usageMapRowLength, format));
  824. ByteBuffer rtn = pageChannel.createPageBuffer();
  825. rtn.put(PageTypes.DATA);
  826. rtn.put((byte) 0x1); //Unknown
  827. rtn.putShort((short)freeSpace); //Free space in page
  828. rtn.putInt(0); //Table definition
  829. rtn.putInt(0); //Unknown
  830. rtn.putShort((short) 2); //Number of records on this page
  831. // write two rows of usage map definitions
  832. int rowStart = findRowEnd(rtn, 0, format) - usageMapRowLength;
  833. for(int i = 0; i < 2; ++i) {
  834. rtn.putShort(getRowStartOffset(i, format), (short)rowStart);
  835. if(i == 0) {
  836. // initial "usage pages" map definition
  837. rtn.put(rowStart, UsageMap.MAP_TYPE_REFERENCE);
  838. } else {
  839. // initial "pages with free space" map definition
  840. rtn.put(rowStart, UsageMap.MAP_TYPE_INLINE);
  841. }
  842. rowStart -= usageMapRowLength;
  843. }
  844. return rtn;
  845. }
  846. /**
  847. * Read the table definition
  848. */
  849. private void readTableDefinition(ByteBuffer tableBuffer) throws IOException
  850. {
  851. if (LOG.isDebugEnabled()) {
  852. tableBuffer.rewind();
  853. LOG.debug("Table def block:\n" + ByteUtil.toHexString(tableBuffer,
  854. getFormat().SIZE_TDEF_HEADER));
  855. }
  856. _rowCount = tableBuffer.getInt(getFormat().OFFSET_NUM_ROWS);
  857. _lastAutoNumber = tableBuffer.getInt(getFormat().OFFSET_NEXT_AUTO_NUMBER);
  858. _tableType = tableBuffer.get(getFormat().OFFSET_TABLE_TYPE);
  859. _maxColumnCount = tableBuffer.getShort(getFormat().OFFSET_MAX_COLS);
  860. _maxVarColumnCount = tableBuffer.getShort(getFormat().OFFSET_NUM_VAR_COLS);
  861. short columnCount = tableBuffer.getShort(getFormat().OFFSET_NUM_COLS);
  862. _indexSlotCount = tableBuffer.getInt(getFormat().OFFSET_NUM_INDEX_SLOTS);
  863. _indexCount = tableBuffer.getInt(getFormat().OFFSET_NUM_INDEXES);
  864. int rowNum = ByteUtil.getUnsignedByte(
  865. tableBuffer, getFormat().OFFSET_OWNED_PAGES);
  866. int pageNum = ByteUtil.get3ByteInt(tableBuffer, getFormat().OFFSET_OWNED_PAGES + 1);
  867. _ownedPages = UsageMap.read(getDatabase(), pageNum, rowNum, false);
  868. rowNum = ByteUtil.getUnsignedByte(
  869. tableBuffer, getFormat().OFFSET_FREE_SPACE_PAGES);
  870. pageNum = ByteUtil.get3ByteInt(tableBuffer, getFormat().OFFSET_FREE_SPACE_PAGES + 1);
  871. _freeSpacePages = UsageMap.read(getDatabase(), pageNum, rowNum, false);
  872. for (int i = 0; i < _indexCount; i++) {
  873. int uniqueEntryCountOffset =
  874. (getFormat().OFFSET_INDEX_DEF_BLOCK +
  875. (i * getFormat().SIZE_INDEX_DEFINITION) + 4);
  876. int uniqueEntryCount = tableBuffer.getInt(uniqueEntryCountOffset);
  877. _indexes.add(createIndex(uniqueEntryCount, uniqueEntryCountOffset));
  878. }
  879. int colOffset = getFormat().OFFSET_INDEX_DEF_BLOCK +
  880. _indexCount * getFormat().SIZE_INDEX_DEFINITION;
  881. for (int i = 0; i < columnCount; i++) {
  882. Column column = new Column(this, tableBuffer,
  883. colOffset + (i * getFormat().SIZE_COLUMN_HEADER));
  884. _columns.add(column);
  885. if(column.isVariableLength()) {
  886. // also shove it in the variable columns list, which is ordered
  887. // differently from the _columns list
  888. _varColumns.add(column);
  889. }
  890. }
  891. tableBuffer.position(colOffset +
  892. (columnCount * getFormat().SIZE_COLUMN_HEADER));
  893. for (int i = 0; i < columnCount; i++) {
  894. Column column = _columns.get(i);
  895. column.setName(readName(tableBuffer));
  896. }
  897. Collections.sort(_columns);
  898. // setup the data index for the columns
  899. int colIdx = 0;
  900. for(Column col : _columns) {
  901. col.setColumnIndex(colIdx++);
  902. }
  903. // sort variable length columns based on their index into the variable
  904. // length offset table, because we will write the columns in this order
  905. Collections.sort(_varColumns, VAR_LEN_COLUMN_COMPARATOR);
  906. int idxOffset = tableBuffer.position();
  907. tableBuffer.position(idxOffset +
  908. (getFormat().OFFSET_INDEX_NUMBER_BLOCK * _indexCount));
  909. // if there are more index slots than indexes, the initial slots are
  910. // always empty/invalid, so we skip that data
  911. int firstRealIdx = (_indexSlotCount - _indexCount);
  912. for (int i = 0; i < _indexSlotCount; i++) {
  913. tableBuffer.getInt(); //Forward past Unknown
  914. tableBuffer.getInt(); //Forward past alternate index number
  915. int indexNumber = tableBuffer.getInt();
  916. tableBuffer.position(tableBuffer.position() + 11);
  917. byte indexType = tableBuffer.get();
  918. tableBuffer.position(tableBuffer.position() + 4);
  919. if(i < firstRealIdx) {
  920. // ignore this info
  921. continue;
  922. }
  923. Index index = _indexes.get(i - firstRealIdx);
  924. index.setIndexNumber(indexNumber);
  925. index.setIndexType(indexType);
  926. }
  927. // read actual index names
  928. for (int i = 0; i < _indexSlotCount; i++) {
  929. if(i < firstRealIdx) {
  930. // for each empty index slot, there is some weird sort of name, skip
  931. // it
  932. skipName(tableBuffer);
  933. continue;
  934. }
  935. _indexes.get(i - firstRealIdx)
  936. .setName(readName(tableBuffer));
  937. }
  938. int idxEndOffset = tableBuffer.position();
  939. Collections.sort(_indexes);
  940. // go back to index column info after sorting
  941. tableBuffer.position(idxOffset);
  942. for (int i = 0; i < _indexCount; i++) {
  943. tableBuffer.getInt(); //Forward past Unknown
  944. _indexes.get(i).read(tableBuffer, _columns);
  945. }
  946. // reset to end of index info
  947. tableBuffer.position(idxEndOffset);
  948. }
  949. /**
  950. * Creates an index with the given initial info.
  951. */
  952. private Index createIndex(int uniqueEntryCount, int uniqueEntryCountOffset)
  953. {
  954. return(_useBigIndex ?
  955. new BigIndex(this, uniqueEntryCount, uniqueEntryCountOffset) :
  956. new SimpleIndex(this, uniqueEntryCount, uniqueEntryCountOffset));
  957. }
  958. /**
  959. * Writes the given page data to the given page number, clears any other
  960. * relevant buffers.
  961. */
  962. private void writeDataPage(ByteBuffer pageBuffer, int pageNumber)
  963. throws IOException
  964. {
  965. // write the page data
  966. getPageChannel().writePage(pageBuffer, pageNumber);
  967. // possibly invalidate the add row buffer if a different data buffer is
  968. // being written (e.g. this happens during deleteRow)
  969. _addRowBufferH.possiblyInvalidate(pageNumber, pageBuffer);
  970. // update modification count so any active RowStates can keep themselves
  971. // up-to-date
  972. ++_modCount;
  973. }
  974. /**
  975. * Returns a name read from the buffer at the current position. The
  976. * expected name format is the name length as a short followed by (length *
  977. * 2) bytes encoded using the {@link JetFormat#CHARSET}
  978. */
  979. private String readName(ByteBuffer buffer) {
  980. int nameLength = ByteUtil.getUnsignedShort(buffer);
  981. byte[] nameBytes = new byte[nameLength];
  982. buffer.get(nameBytes);
  983. return Column.decodeUncompressedText(nameBytes, getFormat());
  984. }
  985. /**
  986. * Skips past a name int the buffer at the current position. The
  987. * expected name format is the same as that for {@link #readName}.
  988. */
  989. private void skipName(ByteBuffer buffer) {
  990. int nameLength = ByteUtil.getUnsignedShort(buffer);
  991. buffer.position(buffer.position() + nameLength);
  992. }
  993. /**
  994. * Converts a map of columnName -> columnValue to an array of row values
  995. * appropriate for a call to {@link #addRow(Object...)}.
  996. */
  997. public Object[] asRow(Map<String,Object> rowMap) {
  998. Object[] row = new Object[_columns.size()];
  999. if(rowMap == null) {
  1000. return row;
  1001. }
  1002. for(Column col : _columns) {
  1003. row[col.getColumnIndex()] = rowMap.get(col.getName());
  1004. }
  1005. return row;
  1006. }
  1007. /**
  1008. * Add a single row to this table and write it to disk
  1009. * <p>
  1010. * Note, if this table has an auto-number column, the value written will be
  1011. * put back into the given row array.
  1012. *
  1013. * @param row row values for a single row. the row will be modified if
  1014. * this table contains an auto-number column, otherwise it
  1015. * will not be modified.
  1016. */
  1017. public void addRow(Object... row) throws IOException {
  1018. addRows(Collections.singletonList(row), _singleRowBufferH);
  1019. }
  1020. /**
  1021. * Add multiple rows to this table, only writing to disk after all
  1022. * rows have been written, and every time a data page is filled. This
  1023. * is much more efficient than calling <code>addRow</code> multiple times.
  1024. * <p>
  1025. * Note, if this table has an auto-number column, the values written will be
  1026. * put back into the given row arrays.
  1027. *
  1028. * @param rows List of Object[] row values. the rows will be modified if
  1029. * this table contains an auto-number column, otherwise they
  1030. * will not be modified.
  1031. */
  1032. public void addRows(List<? extends Object[]> rows) throws IOException {
  1033. addRows(rows, _multiRowBufferH);
  1034. }
  1035. /**
  1036. * Add multiple rows to this table, only writing to disk after all
  1037. * rows have been written, and every time a data page is filled.
  1038. * @param inRows List of Object[] row values
  1039. * @param writeRowBufferH TempBufferHolder used to generate buffers for
  1040. * writing the row data
  1041. */
  1042. private void addRows(List<? extends Object[]> inRows,
  1043. TempBufferHolder writeRowBufferH)
  1044. throws IOException
  1045. {
  1046. // copy the input rows to a modifiable list so we can update the elements
  1047. List<Object[]> rows = new ArrayList<Object[]>(inRows);
  1048. ByteBuffer[] rowData = new ByteBuffer[rows.size()];
  1049. for (int i = 0; i < rows.size(); i++) {
  1050. // we need to make sure the row is the right length (fill with null).
  1051. // note, if the row is copied the caller will not be able to access any
  1052. // generated auto-number value, but if they need that info they should
  1053. // use a row array of the right size!
  1054. Object[] row = rows.get(i);
  1055. if(row.length < _columns.size()) {
  1056. row = dupeRow(row, _columns.size());
  1057. // we copied the row, so put the copy back into the rows list
  1058. rows.set(i, row);
  1059. }
  1060. // write the row of data to a temporary buffer
  1061. rowData[i] = createRow(row, getFormat().MAX_ROW_SIZE,
  1062. writeRowBufferH.getPageBuffer(getPageChannel()));
  1063. if (rowData[i].limit() > getFormat().MAX_ROW_SIZE) {
  1064. throw new IOException("Row size " + rowData[i].limit() +
  1065. " is too large");
  1066. }
  1067. }
  1068. ByteBuffer dataPage = null;
  1069. int pageNumber = PageChannel.INVALID_PAGE_NUMBER;
  1070. // find last data page (Not bothering to check other pages for free
  1071. // space.)
  1072. UsageMap.PageCursor revPageCursor = _ownedPages.cursor();
  1073. revPageCursor.afterLast();
  1074. while(true) {
  1075. int tmpPageNumber = revPageCursor.getPreviousPage();
  1076. if(tmpPageNumber < 0) {
  1077. break;
  1078. }
  1079. dataPage = _addRowBufferH.setPage(getPageChannel(), tmpPageNumber);
  1080. if(dataPage.get() == PageTypes.DATA) {
  1081. // found last data page, only use if actually listed in free space
  1082. // pages
  1083. if(_freeSpacePages.containsPageNumber(tmpPageNumber)) {
  1084. pageNumber = tmpPageNumber;
  1085. }
  1086. break;
  1087. }
  1088. }
  1089. if(pageNumber == PageChannel.INVALID_PAGE_NUMBER) {
  1090. // No data pages exist (with free space). Create a new one.
  1091. dataPage = newDataPage();
  1092. pageNumber = _addRowBufferH.getPageNumber();
  1093. }
  1094. for (int i = 0; i < rowData.length; i++) {
  1095. int rowSize = rowData[i].remaining();
  1096. if(!rowFitsOnDataPage(rowSize, dataPage, getFormat())) {
  1097. // Last data page is full. Create a new one.
  1098. writeDataPage(dataPage, pageNumber);
  1099. _freeSpacePages.removePageNumber(pageNumber);
  1100. dataPage = newDataPage();
  1101. pageNumber = _addRowBufferH.getPageNumber();
  1102. }
  1103. // write out the row data
  1104. int rowNum = addDataPageRow(dataPage, rowSize, getFormat());
  1105. dataPage.put(rowData[i]);
  1106. // update the indexes
  1107. for(Index index : _indexes) {
  1108. index.addRow(rows.get(i), new RowId(pageNumber, rowNum));
  1109. }
  1110. }
  1111. writeDataPage(dataPage, pageNumber);
  1112. // Update tdef page
  1113. updateTableDefinition(rows.size());
  1114. }
  1115. /**
  1116. * Updates the table definition after rows are modified.
  1117. */
  1118. private void updateTableDefinition(int rowCountInc) throws IOException
  1119. {
  1120. // load table definition
  1121. ByteBuffer tdefPage = _tableDefBufferH.setPage(getPageChannel(),
  1122. _tableDefPageNumber);
  1123. // make sure rowcount and autonumber are up-to-date
  1124. _rowCount += rowCountInc;
  1125. tdefPage.putInt(getFormat().OFFSET_NUM_ROWS, _rowCount);
  1126. tdefPage.putInt(getFormat().OFFSET_NEXT_AUTO_NUMBER, _lastAutoNumber);
  1127. // write any index changes
  1128. Iterator<Index> indIter = _indexes.iterator();
  1129. for (int i = 0; i < _indexes.size(); i++) {
  1130. Index index = indIter.next();
  1131. // write the unique entry count for the index to the table definition
  1132. // page
  1133. tdefPage.putInt(index.getUniqueEntryCountOffset(),
  1134. index.getUniqueEntryCount());
  1135. // write the entry page for the index
  1136. index.update();
  1137. }
  1138. // write modified table definition
  1139. getPageChannel().writePage(tdefPage, _tableDefPageNumber);
  1140. }
  1141. /**
  1142. * Create a new data page
  1143. * @return Page number of the new page
  1144. */
  1145. private ByteBuffer newDataPage() throws IOException {
  1146. if (LOG.isDebugEnabled()) {
  1147. LOG.debug("Creating new data page");
  1148. }
  1149. ByteBuffer dataPage = _addRowBufferH.setNewPage(getPageChannel());
  1150. dataPage.put(PageTypes.DATA); //Page type
  1151. dataPage.put((byte) 1); //Unknown
  1152. dataPage.putShort((short)getFormat().PAGE_INITIAL_FREE_SPACE); //Free space in this page
  1153. dataPage.putInt(_tableDefPageNumber); //Page pointer to table definition
  1154. dataPage.putInt(0); //Unknown
  1155. dataPage.putShort((short)0); //Number of rows on this page
  1156. int pageNumber = _addRowBufferH.getPageNumber();
  1157. getPageChannel().writePage(dataPage, pageNumber);
  1158. _ownedPages.addPageNumber(pageNumber);
  1159. _freeSpacePages.addPageNumber(pageNumber);
  1160. return dataPage;
  1161. }
  1162. /**
  1163. * Serialize a row of Objects into a byte buffer.
  1164. * <p>
  1165. * Note, if this table has an auto-number column, the value written will be
  1166. * put back into the given row array.
  1167. *
  1168. * @param rowArray row data, expected to be correct length for this table
  1169. * @param maxRowSize max size the data can be for this row
  1170. * @param buffer buffer to which to write the row data
  1171. * @return the given buffer, filled with the row data
  1172. */
  1173. ByteBuffer createRow(Object[] rowArray, int maxRowSize, ByteBuffer buffer)
  1174. throws IOException
  1175. {
  1176. buffer.putShort(_maxColumnCount);
  1177. NullMask nullMask = new NullMask(_maxColumnCount);
  1178. //Fixed length column data comes first
  1179. int fixedDataStart = buffer.position();
  1180. int fixedDataEnd = fixedDataStart;
  1181. for (Column col : _columns) {
  1182. if(!col.isVariableLength()) {
  1183. Object rowValue = rowArray[col.getColumnIndex()];
  1184. if (col.getType() == DataType.BOOLEAN) {
  1185. if(Column.toBooleanValue(rowValue)) {
  1186. //Booleans are stored in the null mask
  1187. nullMask.markNotNull(col);
  1188. }
  1189. } else {
  1190. if(col.isAutoNumber()) {
  1191. // ignore given row value, use next autonumber
  1192. rowValue = getNextAutoNumber();
  1193. // we need to stick this back in the row so that the indexes get
  1194. // updated correctly (and caller can get the generated value)
  1195. rowArray[col.getColumnIndex()] = rowValue;
  1196. }
  1197. if(rowValue != null) {
  1198. // we have a value
  1199. nullMask.markNotNull(col);
  1200. //remainingRowLength is ignored when writing fixed length data
  1201. buffer.position(fixedDataStart + col.getFixedDataOffset());
  1202. buffer.put(col.write(rowValue, 0));
  1203. // keep track of the end of fixed data
  1204. if(buffer.position() > fixedDataEnd) {
  1205. fixedDataEnd = buffer.position();
  1206. }
  1207. }
  1208. }
  1209. }
  1210. }
  1211. // reposition at end of fixed data
  1212. buffer.position(fixedDataEnd);
  1213. // only need this info if this table contains any var length data
  1214. if(_maxVarColumnCount > 0) {
  1215. // figure out how much space remains for var length data. first,
  1216. // account for already written space
  1217. maxRowSize -= buffer.position();
  1218. // now, account for trailer space
  1219. maxRowSize -= (nullMask.byteSize() + 4 + (_maxVarColumnCount * 2));
  1220. // for each non-null long value column we need to reserve a small
  1221. // amount of space so that we don't end up running out of row space
  1222. // later by being too greedy
  1223. for (Column varCol : _varColumns) {
  1224. if((varCol.getType().isLongValue()) &&
  1225. (rowArray[varCol.getColumnIndex()] != null)) {
  1226. maxRowSize -= getFormat().SIZE_LONG_VALUE_DEF;
  1227. }
  1228. }
  1229. //Now write out variable length column data
  1230. short[] varColumnOffsets = new short[_maxVarColumnCount];
  1231. int varColumnOffsetsIndex = 0;
  1232. for (Column varCol : _varColumns) {
  1233. short offset = (short) buffer.position();
  1234. Object rowValue = rowArray[varCol.getColumnIndex()];
  1235. if (rowValue != null) {
  1236. // we have a value
  1237. nullMask.markNotNull(varCol);
  1238. ByteBuffer varDataBuf = varCol.write(rowValue, maxRowSize);
  1239. maxRowSize -= varDataBuf.remaining();
  1240. if(varCol.getType().isLongValue()) {
  1241. // we already accounted for some amount of the long value data
  1242. // above. add that space back so we don't double count
  1243. maxRowSize += getFormat().SIZE_LONG_VALUE_DEF;
  1244. }
  1245. buffer.put(varDataBuf);
  1246. }
  1247. // we do a loop here so that we fill in offsets for deleted columns
  1248. while(varColumnOffsetsIndex <= varCol.getVarLenTableIndex()) {
  1249. varColumnOffsets[varColumnOffsetsIndex++] = offset;
  1250. }
  1251. }
  1252. // fill in offsets for any remaining deleted columns
  1253. while(varColumnOffsetsIndex < varColumnOffsets.length) {
  1254. varColumnOffsets[varColumnOffsetsIndex++] = (short) buffer.position();
  1255. }
  1256. buffer.putShort((short) buffer.position()); //EOD marker
  1257. //Now write out variable length offsets
  1258. //Offsets are stored in reverse order
  1259. for (int i = _maxVarColumnCount - 1; i >= 0; i--) {
  1260. buffer.putShort(varColumnOffsets[i]);
  1261. }
  1262. buffer.putShort(_maxVarColumnCount); //Number of var length columns
  1263. }
  1264. nullMask.write(buffer); //Null mask
  1265. buffer.flip();
  1266. if (LOG.isDebugEnabled()) {
  1267. LOG.debug("Creating new data block:\n" + ByteUtil.toHexString(buffer, buffer.limit()));
  1268. }
  1269. return buffer;
  1270. }
  1271. public int getRowCount() {
  1272. return _rowCount;
  1273. }
  1274. private int getNextAutoNumber() {
  1275. // note, the saved value is the last one handed out, so pre-increment
  1276. return ++_lastAutoNumber;
  1277. }
  1278. int getLastAutoNumber() {
  1279. // gets the last used auto number (does not modify)
  1280. return _lastAutoNumber;
  1281. }
  1282. @Override
  1283. public String toString() {
  1284. StringBuilder rtn = new StringBuilder();
  1285. rtn.append("Type: " + _tableType);
  1286. rtn.append("\nName: " + _name);
  1287. rtn.append("\nRow count: " + _rowCount);
  1288. rtn.append("\nColumn count: " + _columns.size());
  1289. rtn.append("\nIndex count: " + _indexCount);
  1290. rtn.append("\nColumns:\n");
  1291. for(Column col : _columns) {
  1292. rtn.append(col);
  1293. }
  1294. rtn.append("\nIndexes:\n");
  1295. for(Index index : _indexes) {
  1296. rtn.append(index);
  1297. }
  1298. rtn.append("\nOwned pages: " + _ownedPages + "\n");
  1299. return rtn.toString();
  1300. }
  1301. /**
  1302. * @return A simple String representation of the entire table in tab-delimited format
  1303. */
  1304. public String display() throws IOException {
  1305. return display(Long.MAX_VALUE);
  1306. }
  1307. /**
  1308. * @param limit Maximum number of rows to display
  1309. * @return A simple String representation of the entire table in tab-delimited format
  1310. */
  1311. public String display(long limit) throws IOException {
  1312. reset();
  1313. StringBuilder rtn = new StringBuilder();
  1314. for(Iterator<Column> iter = _columns.iterator(); iter.hasNext(); ) {
  1315. Column col = iter.next();
  1316. rtn.append(col.getName());
  1317. if (iter.hasNext()) {
  1318. rtn.append("\t");
  1319. }
  1320. }
  1321. rtn.append("\n");
  1322. Map<String, Object> row;
  1323. int rowCount = 0;
  1324. while ((rowCount++ < limit) && (row = getNextRow()) != null) {
  1325. for(Iterator<Object> iter = row.values().iterator(); iter.hasNext(); ) {
  1326. Object obj = iter.next();
  1327. if (obj instanceof byte[]) {
  1328. byte[] b = (byte[]) obj;
  1329. rtn.append(ByteUtil.toHexString(b));
  1330. //This block can be used to easily dump a binary column to a file
  1331. /*java.io.File f = java.io.File.createTempFile("ole", ".bin");
  1332. java.io.FileOutputStream out = new java.io.FileOutputStream(f);
  1333. out.write(b);
  1334. out.flush();
  1335. out.close();*/
  1336. } else {
  1337. rtn.append(String.valueOf(obj));
  1338. }
  1339. if (iter.hasNext()) {
  1340. rtn.append("\t");
  1341. }
  1342. }
  1343. rtn.append("\n");
  1344. }
  1345. return rtn.toString();
  1346. }
  1347. /**
  1348. * Updates free space and row info for a new row of the given size in the
  1349. * given data page. Positions the page for writing the row data.
  1350. * @return the row number of the new row
  1351. */
  1352. public static int addDataPageRow(ByteBuffer dataPage,
  1353. int rowSize,
  1354. JetFormat format)
  1355. {
  1356. int rowSpaceUsage = getRowSpaceUsage(rowSize, format);
  1357. // Decrease free space record.
  1358. short freeSpaceInPage = dataPage.getShort(format.OFFSET_FREE_SPACE);
  1359. dataPage.putShort(format.OFFSET_FREE_SPACE, (short) (freeSpaceInPage -
  1360. rowSpaceUsage));
  1361. // Increment row count record.
  1362. short rowCount = dataPage.getShort(format.OFFSET_NUM_ROWS_ON_DATA_PAGE);
  1363. dataPage.putShort(format.OFFSET_NUM_ROWS_ON_DATA_PAGE,
  1364. (short) (rowCount + 1));
  1365. // determine row position
  1366. short rowLocation = findRowEnd(dataPage, rowCount, format);
  1367. rowLocation -= rowSize;
  1368. // write row position
  1369. dataPage.putShort(getRowStartOffset(rowCount, format), rowLocation);
  1370. // set position for row data
  1371. dataPage.position(rowLocation);
  1372. return rowCount;
  1373. }
  1374. /**
  1375. * Returns the row count for the current page. If the page is invalid
  1376. * ({@code null}) or the page is not a DATA page, 0 is returned.
  1377. */
  1378. private static int getRowsOnDataPage(ByteBuffer rowBuffer, JetFormat format)
  1379. throws IOException
  1380. {
  1381. int rowsOnPage = 0;
  1382. if((rowBuffer != null) && (rowBuffer.get(0) == PageTypes.DATA)) {
  1383. rowsOnPage = rowBuffer.getShort(format.OFFSET_NUM_ROWS_ON_DATA_PAGE);
  1384. }
  1385. return rowsOnPage;
  1386. }
  1387. /**
  1388. * @throws IllegalStateException if the given rowId is invalid
  1389. */
  1390. private static void requireValidRowId(RowId rowId) {
  1391. if(!rowId.isValid()) {
  1392. throw new IllegalArgumentException("Given rowId is invalid: " + rowId);
  1393. }
  1394. }
  1395. /**
  1396. * @throws IllegalStateException if the given row is invalid or deleted
  1397. */
  1398. private static void requireNonDeletedRow(RowState rowState, RowId rowId) {
  1399. if(!rowState.isValid()) {
  1400. throw new IllegalArgumentException(
  1401. "Given rowId is invalid for this table: " + rowId);
  1402. }
  1403. if(rowState.isDeleted()) {
  1404. throw new IllegalStateException("Row is deleted: " + rowId);
  1405. }
  1406. }
  1407. public static boolean isDeletedRow(short rowStart) {
  1408. return ((rowStart & DELETED_ROW_MASK) != 0);
  1409. }
  1410. public static boolean isOverflowRow(short rowStart) {
  1411. return ((rowStart & OVERFLOW_ROW_MASK) != 0);
  1412. }
  1413. public static short cleanRowStart(short rowStart) {
  1414. return (short)(rowStart & OFFSET_MASK);
  1415. }
  1416. public static short findRowStart(ByteBuffer buffer, int rowNum,
  1417. JetFormat format)
  1418. {
  1419. return cleanRowStart(
  1420. buffer.getShort(getRowStartOffset(rowNum, format)));
  1421. }
  1422. public static int getRowStartOffset(int rowNum, JetFormat format)
  1423. {
  1424. return format.OFFSET_ROW_START + (format.SIZE_ROW_LOCATION * rowNum);
  1425. }
  1426. public static short findRowEnd(ByteBuffer buffer, int rowNum,
  1427. JetFormat format)
  1428. {
  1429. return (short)((rowNum == 0) ?
  1430. format.PAGE_SIZE :
  1431. cleanRowStart(
  1432. buffer.getShort(getRowEndOffset(rowNum, format))));
  1433. }
  1434. public static int getRowEndOffset(int rowNum, JetFormat format)
  1435. {
  1436. return format.OFFSET_ROW_START + (format.SIZE_ROW_LOCATION * (rowNum - 1));
  1437. }
  1438. public static int getRowSpaceUsage(int rowSize, JetFormat format)
  1439. {
  1440. return rowSize + format.SIZE_ROW_LOCATION;
  1441. }
  1442. /**
  1443. * @return the number of "AutoNumber" columns in the given collection of
  1444. * columns.
  1445. */
  1446. public static int countAutoNumberColumns(Collection<Column> columns) {
  1447. int numAutoNumCols = 0;
  1448. for(Column c : columns) {
  1449. if(c.isAutoNumber()) {
  1450. ++numAutoNumCols;
  1451. }
  1452. }
  1453. return numAutoNumCols;
  1454. }
  1455. /**
  1456. * Returns {@code true} if a row of the given size will fit on the given
  1457. * data page, {@code false} otherwise.
  1458. */
  1459. public static boolean rowFitsOnDataPage(
  1460. int rowLength, ByteBuffer dataPage, JetFormat format)
  1461. throws IOException
  1462. {
  1463. int rowSpaceUsage = getRowSpaceUsage(rowLength, format);
  1464. short freeSpaceInPage = dataPage.getShort(format.OFFSET_FREE_SPACE);
  1465. int rowsOnPage = getRowsOnDataPage(dataPage, format);
  1466. return ((rowSpaceUsage <= freeSpaceInPage) &&
  1467. (rowsOnPage < format.MAX_NUM_ROWS_ON_DATA_PAGE));
  1468. }
  1469. /**
  1470. * Duplicates and returns a row of data, optionally with a longer length
  1471. * filled with {@code null}.
  1472. */
  1473. static Object[] dupeRow(Object[] row, int newRowLength) {
  1474. Object[] copy = new Object[newRowLength];
  1475. System.arraycopy(row, 0, copy, 0, row.length);
  1476. return copy;
  1477. }
  1478. /** various statuses for the row data */
  1479. private enum RowStatus {
  1480. INIT, INVALID_PAGE, INVALID_ROW, VALID, DELETED, NORMAL, OVERFLOW;
  1481. }
  1482. /** the phases the RowState moves through as the data is parsed */
  1483. private enum RowStateStatus {
  1484. INIT, AT_HEADER, AT_FINAL;
  1485. }
  1486. /**
  1487. * Maintains the state of reading a row of data.
  1488. */
  1489. public final class RowState
  1490. {
  1491. /** Buffer used for reading the header row data pages */
  1492. private final TempPageHolder _headerRowBufferH;
  1493. /** the header rowId */
  1494. private RowId _headerRowId = RowId.FIRST_ROW_ID;
  1495. /** the number of rows on the header page */
  1496. private int _rowsOnHeaderPage;
  1497. /** the rowState status */
  1498. private RowStateStatus _status = RowStateStatus.INIT;
  1499. /** the row status */
  1500. private RowStatus _rowStatus = RowStatus.INIT;
  1501. /** buffer used for reading overflow pages */
  1502. private final TempPageHolder _overflowRowBufferH =
  1503. TempPageHolder.newHolder(TempBufferHolder.Type.SOFT);
  1504. /** the row buffer which contains the final data (after following any
  1505. overflow pointers) */
  1506. private ByteBuffer _finalRowBuffer;
  1507. /** the rowId which contains the final data (after following any overflow
  1508. pointers) */
  1509. private RowId _finalRowId = null;
  1510. /** true if the row values array has data */
  1511. private boolean _haveRowValues;
  1512. /** values read from the last row */
  1513. private final Object[] _rowValues;
  1514. /** last modification count seen on the table we track this so that the
  1515. rowState can detect updates to the table and re-read any buffered
  1516. data */
  1517. private int _lastModCount;
  1518. /** optional error handler to use when row errors are encountered */
  1519. private ErrorHandler _errorHandler;
  1520. private RowState(TempBufferHolder.Type headerType) {
  1521. _headerRowBufferH = TempPageHolder.newHolder(headerType);
  1522. _rowValues = new Object[Table.this.getColumnCount()];
  1523. _lastModCount = Table.this._modCount;
  1524. }
  1525. public Table getTable() {
  1526. return Table.this;
  1527. }
  1528. public ErrorHandler getErrorHandler() {
  1529. return((_errorHandler != null) ? _errorHandler :
  1530. getTable().getErrorHandler());
  1531. }
  1532. public void setErrorHandler(ErrorHandler newErrorHandler) {
  1533. _errorHandler = newErrorHandler;
  1534. }
  1535. public void reset() {
  1536. _finalRowId = null;
  1537. _finalRowBuffer = null;
  1538. _rowsOnHeaderPage = 0;
  1539. _status = RowStateStatus.INIT;
  1540. _rowStatus = RowStatus.INIT;
  1541. if(_haveRowValues) {
  1542. Arrays.fill(_rowValues, null);
  1543. _haveRowValues = false;
  1544. }
  1545. }
  1546. public boolean isUpToDate() {
  1547. return(Table.this._modCount == _lastModCount);
  1548. }
  1549. private void checkForModification() {
  1550. if(!isUpToDate()) {
  1551. reset();
  1552. _headerRowBufferH.invalidate();
  1553. _overflowRowBufferH.invalidate();
  1554. _lastModCount = Table.this._modCount;
  1555. }
  1556. }
  1557. private ByteBuffer getFinalPage()
  1558. throws IOException
  1559. {
  1560. if(_finalRowBuffer == null) {
  1561. // (re)load current page
  1562. _finalRowBuffer = getHeaderPage();
  1563. }
  1564. return _finalRowBuffer;
  1565. }
  1566. public RowId getFinalRowId() {
  1567. if(_finalRowId == null) {
  1568. _finalRowId = getHeaderRowId();
  1569. }
  1570. return _finalRowId;
  1571. }
  1572. private void setRowStatus(RowStatus rowStatus) {
  1573. _rowStatus = rowStatus;
  1574. }
  1575. public boolean isValid() {
  1576. return(_rowStatus.ordinal() >= RowStatus.VALID.ordinal());
  1577. }
  1578. public boolean isDeleted() {
  1579. return(_rowStatus == RowStatus.DELETED);
  1580. }
  1581. public boolean isOverflow() {
  1582. return(_rowStatus == RowStatus.OVERFLOW);
  1583. }
  1584. public boolean isHeaderPageNumberValid() {
  1585. return(_rowStatus.ordinal() > RowStatus.INVALID_PAGE.ordinal());
  1586. }
  1587. public boolean isHeaderRowNumberValid() {
  1588. return(_rowStatus.ordinal() > RowStatus.INVALID_ROW.ordinal());
  1589. }
  1590. private void setStatus(RowStateStatus status) {
  1591. _status = status;
  1592. }
  1593. public boolean isAtHeaderRow() {
  1594. return(_status.ordinal() >= RowStateStatus.AT_HEADER.ordinal());
  1595. }
  1596. public boolean isAtFinalRow() {
  1597. return(_status.ordinal() >= RowStateStatus.AT_FINAL.ordinal());
  1598. }
  1599. private void setRowValue(int idx, Object value) {
  1600. _haveRowValues = true;
  1601. _rowValues[idx] = value;
  1602. }
  1603. public Object[] getRowValues() {
  1604. return dupeRow(_rowValues, _rowValues.length);
  1605. }
  1606. public RowId getHeaderRowId() {
  1607. return _headerRowId;
  1608. }
  1609. public int getRowsOnHeaderPage() {
  1610. return _rowsOnHeaderPage;
  1611. }
  1612. private ByteBuffer getHeaderPage()
  1613. throws IOException
  1614. {
  1615. checkForModification();
  1616. return _headerRowBufferH.getPage(getPageChannel());
  1617. }
  1618. private ByteBuffer setHeaderRow(RowId rowId)
  1619. throws IOException
  1620. {
  1621. checkForModification();
  1622. // don't do any work if we are already positioned correctly
  1623. if(isAtHeaderRow() && (getHeaderRowId().equals(rowId))) {
  1624. return(isValid() ? getHeaderPage() : null);
  1625. }
  1626. // rejigger everything
  1627. reset();
  1628. _headerRowId = rowId;
  1629. _finalRowId = rowId;
  1630. int pageNumber = rowId.getPageNumber();
  1631. int rowNumber = rowId.getRowNumber();
  1632. if((pageNumber < 0) || !_ownedPages.containsPageNumber(pageNumber)) {
  1633. setRowStatus(RowStatus.INVALID_PAGE);
  1634. return null;
  1635. }
  1636. _finalRowBuffer = _headerRowBufferH.setPage(getPageChannel(),
  1637. pageNumber);
  1638. _rowsOnHeaderPage = getRowsOnDataPage(_finalRowBuffer, getFormat());
  1639. if((rowNumber < 0) || (rowNumber >= _rowsOnHeaderPage)) {
  1640. setRowStatus(RowStatus.INVALID_ROW);
  1641. return null;
  1642. }
  1643. setRowStatus(RowStatus.VALID);
  1644. return _finalRowBuffer;
  1645. }
  1646. private ByteBuffer setOverflowRow(RowId rowId)
  1647. throws IOException
  1648. {
  1649. // this should never see modifications because it only happens within
  1650. // the positionAtRowData method
  1651. if(!isUpToDate()) {
  1652. throw new IllegalStateException("Table modified while searching?");
  1653. }
  1654. if(_rowStatus != RowStatus.OVERFLOW) {
  1655. throw new IllegalStateException("Row is not an overflow row?");
  1656. }
  1657. _finalRowId = rowId;
  1658. _finalRowBuffer = _overflowRowBufferH.setPage(getPageChannel(),
  1659. rowId.getPageNumber());
  1660. return _finalRowBuffer;
  1661. }
  1662. private Object handleRowError(Column column,
  1663. byte[] columnData,
  1664. Exception error)
  1665. throws IOException
  1666. {
  1667. return getErrorHandler().handleRowError(column, columnData,
  1668. this, error);
  1669. }
  1670. @Override
  1671. public String toString()
  1672. {
  1673. return "RowState: headerRowId = " + _headerRowId + ", finalRowId = " +
  1674. _finalRowId;
  1675. }
  1676. }
  1677. }