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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496
  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.nio.charset.Charset;
  26. import java.util.ArrayList;
  27. import java.util.Arrays;
  28. import java.util.Collection;
  29. import java.util.Collections;
  30. import java.util.Comparator;
  31. import java.util.HashMap;
  32. import java.util.Iterator;
  33. import java.util.LinkedHashMap;
  34. import java.util.List;
  35. import java.util.Map;
  36. import org.apache.commons.logging.Log;
  37. import org.apache.commons.logging.LogFactory;
  38. /**
  39. * A single database table
  40. * <p>
  41. * Is not thread-safe.
  42. *
  43. * @author Tim McCune
  44. * @usage _general_class_
  45. */
  46. public class Table
  47. implements Iterable<Map<String, Object>>
  48. {
  49. private static final Log LOG = LogFactory.getLog(Table.class);
  50. private static final short OFFSET_MASK = (short)0x1FFF;
  51. private static final short DELETED_ROW_MASK = (short)0x8000;
  52. private static final short OVERFLOW_ROW_MASK = (short)0x4000;
  53. static final int MAGIC_TABLE_NUMBER = 1625;
  54. private static final int MAX_BYTE = 256;
  55. /**
  56. * Table type code for system tables
  57. * @usage _intermediate_class_
  58. */
  59. public static final byte TYPE_SYSTEM = 0x53;
  60. /**
  61. * Table type code for user tables
  62. * @usage _intermediate_class_
  63. */
  64. public static final byte TYPE_USER = 0x4e;
  65. /**
  66. * enum which controls the ordering of the columns in a table.
  67. * @usage _intermediate_class_
  68. */
  69. public enum ColumnOrder {
  70. /** columns are ordered based on the order of the data in the table (this
  71. order does not change as columns are added to the table). */
  72. DATA,
  73. /** columns are ordered based on the "display" order (this order can be
  74. changed arbitrarily) */
  75. DISPLAY;
  76. }
  77. /** comparator which sorts variable length columns based on their index into
  78. the variable length offset table */
  79. private static final Comparator<Column> VAR_LEN_COLUMN_COMPARATOR =
  80. new Comparator<Column>() {
  81. public int compare(Column c1, Column c2) {
  82. return ((c1.getVarLenTableIndex() < c2.getVarLenTableIndex()) ? -1 :
  83. ((c1.getVarLenTableIndex() > c2.getVarLenTableIndex()) ? 1 :
  84. 0));
  85. }
  86. };
  87. /** comparator which sorts columns based on their display index */
  88. private static final Comparator<Column> DISPLAY_ORDER_COMPARATOR =
  89. new Comparator<Column>() {
  90. public int compare(Column c1, Column c2) {
  91. return ((c1.getDisplayIndex() < c2.getDisplayIndex()) ? -1 :
  92. ((c1.getDisplayIndex() > c2.getDisplayIndex()) ? 1 :
  93. 0));
  94. }
  95. };
  96. /** owning database */
  97. private final Database _database;
  98. /** additional table flags from the catalog entry */
  99. private int _flags;
  100. /** Type of the table (either TYPE_SYSTEM or TYPE_USER) */
  101. private byte _tableType;
  102. /** Number of actual indexes on the table */
  103. private int _indexCount;
  104. /** Number of logical indexes for the table */
  105. private int _logicalIndexCount;
  106. /** Number of rows in the table */
  107. private int _rowCount;
  108. /** last long auto number for the table */
  109. private int _lastLongAutoNumber;
  110. /** last complex type auto number for the table */
  111. private int _lastComplexTypeAutoNumber;
  112. /** page number of the definition of this table */
  113. private final int _tableDefPageNumber;
  114. /** max Number of columns in the table (includes previous deletions) */
  115. private short _maxColumnCount;
  116. /** max Number of variable columns in the table */
  117. private short _maxVarColumnCount;
  118. /** List of columns in this table, ordered by column number */
  119. private List<Column> _columns = new ArrayList<Column>();
  120. /** List of variable length columns in this table, ordered by offset */
  121. private List<Column> _varColumns = new ArrayList<Column>();
  122. /** List of autonumber columns in this table, ordered by column number */
  123. private List<Column> _autoNumColumns;
  124. /** List of indexes on this table (multiple logical indexes may be backed by
  125. the same index data) */
  126. private List<Index> _indexes = new ArrayList<Index>();
  127. /** List of index datas on this table (the actual backing data for an
  128. index) */
  129. private List<IndexData> _indexDatas = new ArrayList<IndexData>();
  130. /** Table name as stored in Database */
  131. private final String _name;
  132. /** Usage map of pages that this table owns */
  133. private UsageMap _ownedPages;
  134. /** Usage map of pages that this table owns with free space on them */
  135. private UsageMap _freeSpacePages;
  136. /** modification count for the table, keeps row-states up-to-date */
  137. private int _modCount;
  138. /** page buffer used to update data pages when adding rows */
  139. private final TempPageHolder _addRowBufferH =
  140. TempPageHolder.newHolder(TempBufferHolder.Type.SOFT);
  141. /** page buffer used to update the table def page */
  142. private final TempPageHolder _tableDefBufferH =
  143. TempPageHolder.newHolder(TempBufferHolder.Type.SOFT);
  144. /** buffer used to writing single rows of data */
  145. private final TempBufferHolder _singleRowBufferH =
  146. TempBufferHolder.newHolder(TempBufferHolder.Type.SOFT, true);
  147. /** "buffer" used to writing multi rows of data (will create new buffer on
  148. every call) */
  149. private final TempBufferHolder _multiRowBufferH =
  150. TempBufferHolder.newHolder(TempBufferHolder.Type.NONE, true);
  151. /** page buffer used to write out-of-line "long value" data */
  152. private final TempPageHolder _longValueBufferH =
  153. TempPageHolder.newHolder(TempBufferHolder.Type.SOFT);
  154. /** "big index support" is optional */
  155. private final boolean _useBigIndex;
  156. /** optional error handler to use when row errors are encountered */
  157. private ErrorHandler _tableErrorHandler;
  158. /** properties for this table */
  159. private PropertyMap _props;
  160. /** properties group for this table (and columns) */
  161. private PropertyMaps _propertyMaps;
  162. /** common cursor for iterating through the table, kept here for historic
  163. reasons */
  164. private Cursor _cursor;
  165. /**
  166. * Only used by unit tests
  167. */
  168. Table(boolean testing, List<Column> columns) throws IOException {
  169. if(!testing) {
  170. throw new IllegalArgumentException();
  171. }
  172. _database = null;
  173. _tableDefPageNumber = PageChannel.INVALID_PAGE_NUMBER;
  174. _name = null;
  175. _useBigIndex = true;
  176. setColumns(columns);
  177. }
  178. /**
  179. * @param database database which owns this table
  180. * @param tableBuffer Buffer to read the table with
  181. * @param pageNumber Page number of the table definition
  182. * @param name Table name
  183. * @param useBigIndex whether or not "big index support" should be enabled
  184. * for the table
  185. */
  186. protected Table(Database database, ByteBuffer tableBuffer,
  187. int pageNumber, String name, int flags, boolean useBigIndex)
  188. throws IOException
  189. {
  190. _database = database;
  191. _tableDefPageNumber = pageNumber;
  192. _name = name;
  193. _flags = flags;
  194. _useBigIndex = useBigIndex;
  195. int nextPage = tableBuffer.getInt(getFormat().OFFSET_NEXT_TABLE_DEF_PAGE);
  196. ByteBuffer nextPageBuffer = null;
  197. while (nextPage != 0) {
  198. if (nextPageBuffer == null) {
  199. nextPageBuffer = getPageChannel().createPageBuffer();
  200. }
  201. getPageChannel().readPage(nextPageBuffer, nextPage);
  202. nextPage = nextPageBuffer.getInt(getFormat().OFFSET_NEXT_TABLE_DEF_PAGE);
  203. ByteBuffer newBuffer = getPageChannel().createBuffer(
  204. tableBuffer.capacity() + getFormat().PAGE_SIZE - 8);
  205. newBuffer.put(tableBuffer);
  206. newBuffer.put(nextPageBuffer.array(), 8, getFormat().PAGE_SIZE - 8);
  207. tableBuffer = newBuffer;
  208. tableBuffer.flip();
  209. }
  210. readTableDefinition(tableBuffer);
  211. tableBuffer = null;
  212. }
  213. /**
  214. * @return The name of the table
  215. * @usage _general_method_
  216. */
  217. public String getName() {
  218. return _name;
  219. }
  220. /**
  221. * Whether or not this table has been marked as hidden.
  222. * @usage _general_method_
  223. */
  224. public boolean isHidden() {
  225. return((_flags & Database.HIDDEN_OBJECT_FLAG) != 0);
  226. }
  227. /**
  228. * @usage _advanced_method_
  229. */
  230. public boolean doUseBigIndex() {
  231. return _useBigIndex;
  232. }
  233. /**
  234. * @usage _advanced_method_
  235. */
  236. public int getMaxColumnCount() {
  237. return _maxColumnCount;
  238. }
  239. /**
  240. * @usage _general_method_
  241. */
  242. public int getColumnCount() {
  243. return _columns.size();
  244. }
  245. /**
  246. * @usage _general_method_
  247. */
  248. public Database getDatabase() {
  249. return _database;
  250. }
  251. /**
  252. * @usage _advanced_method_
  253. */
  254. public JetFormat getFormat() {
  255. return getDatabase().getFormat();
  256. }
  257. /**
  258. * @usage _advanced_method_
  259. */
  260. public PageChannel getPageChannel() {
  261. return getDatabase().getPageChannel();
  262. }
  263. /**
  264. * Gets the currently configured ErrorHandler (always non-{@code null}).
  265. * This will be used to handle all errors unless overridden at the Cursor
  266. * level.
  267. * @usage _intermediate_method_
  268. */
  269. public ErrorHandler getErrorHandler() {
  270. return((_tableErrorHandler != null) ? _tableErrorHandler :
  271. getDatabase().getErrorHandler());
  272. }
  273. /**
  274. * Sets a new ErrorHandler. If {@code null}, resets to using the
  275. * ErrorHandler configured at the Database level.
  276. * @usage _intermediate_method_
  277. */
  278. public void setErrorHandler(ErrorHandler newErrorHandler) {
  279. _tableErrorHandler = newErrorHandler;
  280. }
  281. public int getTableDefPageNumber() {
  282. return _tableDefPageNumber;
  283. }
  284. /**
  285. * @usage _advanced_method_
  286. */
  287. public RowState createRowState() {
  288. return new RowState(TempBufferHolder.Type.HARD);
  289. }
  290. protected UsageMap.PageCursor getOwnedPagesCursor() {
  291. return _ownedPages.cursor();
  292. }
  293. /**
  294. * Returns the <i>approximate</i> number of database pages owned by this
  295. * table and all related indexes (this number does <i>not</i> take into
  296. * account pages used for large OLE/MEMO fields).
  297. * <p>
  298. * To calculate the approximate number of bytes owned by a table:
  299. * <code>
  300. * int approxTableBytes = (table.getApproximateOwnedPageCount() *
  301. * table.getFormat().PAGE_SIZE);
  302. * </code>
  303. * @usage _intermediate_method_
  304. */
  305. public int getApproximateOwnedPageCount() {
  306. // add a page for the table def (although that might actually be more than
  307. // one page)
  308. int count = _ownedPages.getPageCount() + 1;
  309. // note, we count owned pages from _physical_ indexes, not logical indexes
  310. // (otherwise we could double count pages)
  311. for(IndexData indexData : _indexDatas) {
  312. count += indexData.getOwnedPageCount();
  313. }
  314. return count;
  315. }
  316. protected TempPageHolder getLongValueBuffer() {
  317. return _longValueBufferH;
  318. }
  319. /**
  320. * @return All of the columns in this table (unmodifiable List)
  321. * @usage _general_method_
  322. */
  323. public List<Column> getColumns() {
  324. return Collections.unmodifiableList(_columns);
  325. }
  326. /**
  327. * @return the column with the given name
  328. * @usage _general_method_
  329. */
  330. public Column getColumn(String name) {
  331. for(Column column : _columns) {
  332. if(column.getName().equalsIgnoreCase(name)) {
  333. return column;
  334. }
  335. }
  336. throw new IllegalArgumentException("Column with name " + name +
  337. " does not exist in this table");
  338. }
  339. /**
  340. * Only called by unit tests
  341. */
  342. private void setColumns(List<Column> columns) {
  343. _columns = columns;
  344. int colIdx = 0;
  345. int varLenIdx = 0;
  346. int fixedOffset = 0;
  347. for(Column col : _columns) {
  348. col.setColumnNumber((short)colIdx);
  349. col.setColumnIndex(colIdx++);
  350. if(col.isVariableLength()) {
  351. col.setVarLenTableIndex(varLenIdx++);
  352. _varColumns.add(col);
  353. } else {
  354. col.setFixedDataOffset(fixedOffset);
  355. fixedOffset += col.getType().getFixedSize();
  356. }
  357. }
  358. _maxColumnCount = (short)_columns.size();
  359. _maxVarColumnCount = (short)_varColumns.size();
  360. _autoNumColumns = getAutoNumberColumns(columns);
  361. }
  362. /**
  363. * @return the properties for this table
  364. * @usage _general_method_
  365. */
  366. public PropertyMap getProperties() throws IOException {
  367. if(_props == null) {
  368. _props = getPropertyMaps().getDefault();
  369. }
  370. return _props;
  371. }
  372. /**
  373. * @return all PropertyMaps for this table (and columns)
  374. * @usage _general_method_
  375. */
  376. protected PropertyMaps getPropertyMaps() throws IOException {
  377. if(_propertyMaps == null) {
  378. _propertyMaps = getDatabase().getPropertiesForObject(
  379. _tableDefPageNumber);
  380. }
  381. return _propertyMaps;
  382. }
  383. /**
  384. * @return All of the Indexes on this table (unmodifiable List)
  385. * @usage _intermediate_method_
  386. */
  387. public List<Index> getIndexes() {
  388. return Collections.unmodifiableList(_indexes);
  389. }
  390. /**
  391. * @return the index with the given name
  392. * @throws IllegalArgumentException if there is no index with the given name
  393. * @usage _intermediate_method_
  394. */
  395. public Index getIndex(String name) {
  396. for(Index index : _indexes) {
  397. if(index.getName().equalsIgnoreCase(name)) {
  398. return index;
  399. }
  400. }
  401. throw new IllegalArgumentException("Index with name " + name +
  402. " does not exist on this table");
  403. }
  404. /**
  405. * @return the primary key index for this table
  406. * @throws IllegalArgumentException if there is no primary key index on this
  407. * table
  408. * @usage _intermediate_method_
  409. */
  410. public Index getPrimaryKeyIndex() {
  411. for(Index index : _indexes) {
  412. if(index.isPrimaryKey()) {
  413. return index;
  414. }
  415. }
  416. throw new IllegalArgumentException("Table " + getName() +
  417. " does not have a primary key index");
  418. }
  419. /**
  420. * @return the foreign key index joining this table to the given other table
  421. * @throws IllegalArgumentException if there is no relationship between this
  422. * table and the given table
  423. * @usage _intermediate_method_
  424. */
  425. public Index getForeignKeyIndex(Table otherTable) {
  426. for(Index index : _indexes) {
  427. if(index.isForeignKey() && (index.getReference() != null) &&
  428. (index.getReference().getOtherTablePageNumber() ==
  429. otherTable.getTableDefPageNumber())) {
  430. return index;
  431. }
  432. }
  433. throw new IllegalArgumentException(
  434. "Table " + getName() + " does not have a foreign key reference to " +
  435. otherTable.getName());
  436. }
  437. /**
  438. * @return All of the IndexData on this table (unmodifiable List)
  439. */
  440. List<IndexData> getIndexDatas() {
  441. return Collections.unmodifiableList(_indexDatas);
  442. }
  443. /**
  444. * Only called by unit tests
  445. */
  446. int getLogicalIndexCount() {
  447. return _logicalIndexCount;
  448. }
  449. private Cursor getInternalCursor() {
  450. if(_cursor == null) {
  451. _cursor = Cursor.createCursor(this);
  452. }
  453. return _cursor;
  454. }
  455. /**
  456. * After calling this method, getNextRow will return the first row in the
  457. * table, see {@link Cursor#reset}.
  458. * @usage _general_method_
  459. */
  460. public void reset() {
  461. getInternalCursor().reset();
  462. }
  463. /**
  464. * Delete the current row (retrieved by a call to {@link #getNextRow()}).
  465. * @usage _general_method_
  466. */
  467. public void deleteCurrentRow() throws IOException {
  468. getInternalCursor().deleteCurrentRow();
  469. }
  470. /**
  471. * Delete the row on which the given rowState is currently positioned.
  472. * <p>
  473. * Note, this method is not generally meant to be used directly. You should
  474. * use the {@link #deleteCurrentRow} method or use the Cursor class, which
  475. * allows for more complex table interactions.
  476. * @usage _advanced_method_
  477. */
  478. public void deleteRow(RowState rowState, RowId rowId) throws IOException {
  479. requireValidRowId(rowId);
  480. // ensure that the relevant row state is up-to-date
  481. ByteBuffer rowBuffer = positionAtRowHeader(rowState, rowId);
  482. requireNonDeletedRow(rowState, rowId);
  483. // delete flag always gets set in the "header" row (even if data is on
  484. // overflow row)
  485. int pageNumber = rowState.getHeaderRowId().getPageNumber();
  486. int rowNumber = rowState.getHeaderRowId().getRowNumber();
  487. // use any read rowValues to help update the indexes
  488. Object[] rowValues = (!_indexDatas.isEmpty() ?
  489. rowState.getRowValues() : null);
  490. int rowIndex = getRowStartOffset(rowNumber, getFormat());
  491. rowBuffer.putShort(rowIndex, (short)(rowBuffer.getShort(rowIndex)
  492. | DELETED_ROW_MASK | OVERFLOW_ROW_MASK));
  493. writeDataPage(rowBuffer, pageNumber);
  494. // update the indexes
  495. for(IndexData indexData : _indexDatas) {
  496. indexData.deleteRow(rowValues, rowId);
  497. }
  498. // make sure table def gets updated
  499. updateTableDefinition(-1);
  500. }
  501. /**
  502. * @return The next row in this table (Column name -> Column value)
  503. * @usage _general_method_
  504. */
  505. public Map<String, Object> getNextRow() throws IOException {
  506. return getNextRow(null);
  507. }
  508. /**
  509. * @param columnNames Only column names in this collection will be returned
  510. * @return The next row in this table (Column name -> Column value)
  511. * @usage _general_method_
  512. */
  513. public Map<String, Object> getNextRow(Collection<String> columnNames)
  514. throws IOException
  515. {
  516. return getInternalCursor().getNextRow(columnNames);
  517. }
  518. /**
  519. * Reads a single column from the given row.
  520. * <p>
  521. * Note, this method is not generally meant to be used directly. Instead
  522. * use the Cursor class, which allows for more complex table interactions,
  523. * e.g. {@link Cursor#getCurrentRowValue}.
  524. * @usage _advanced_method_
  525. */
  526. public Object getRowValue(RowState rowState, RowId rowId, Column column)
  527. throws IOException
  528. {
  529. if(this != column.getTable()) {
  530. throw new IllegalArgumentException(
  531. "Given column " + column + " is not from this table");
  532. }
  533. requireValidRowId(rowId);
  534. // position at correct row
  535. ByteBuffer rowBuffer = positionAtRowData(rowState, rowId);
  536. requireNonDeletedRow(rowState, rowId);
  537. return getRowColumn(getFormat(), rowBuffer, column, rowState, null);
  538. }
  539. /**
  540. * Reads some columns from the given row.
  541. * @param columnNames Only column names in this collection will be returned
  542. * @usage _advanced_method_
  543. */
  544. public Map<String, Object> getRow(
  545. RowState rowState, RowId rowId, Collection<String> columnNames)
  546. throws IOException
  547. {
  548. requireValidRowId(rowId);
  549. // position at correct row
  550. ByteBuffer rowBuffer = positionAtRowData(rowState, rowId);
  551. requireNonDeletedRow(rowState, rowId);
  552. return getRow(getFormat(), rowState, rowBuffer, _columns, columnNames);
  553. }
  554. /**
  555. * Reads the row data from the given row buffer. Leaves limit unchanged.
  556. * Saves parsed row values to the given rowState.
  557. */
  558. private static Map<String, Object> getRow(
  559. JetFormat format,
  560. RowState rowState,
  561. ByteBuffer rowBuffer,
  562. Collection<Column> columns,
  563. Collection<String> columnNames)
  564. throws IOException
  565. {
  566. Map<String, Object> rtn = new LinkedHashMap<String, Object>(
  567. columns.size());
  568. for(Column column : columns) {
  569. if((columnNames == null) || (columnNames.contains(column.getName()))) {
  570. // Add the value to the row data
  571. column.setRowValue(
  572. rtn, getRowColumn(format, rowBuffer, column, rowState, null));
  573. }
  574. }
  575. return rtn;
  576. }
  577. /**
  578. * Reads the column data from the given row buffer. Leaves limit unchanged.
  579. * Caches the returned value in the rowState.
  580. */
  581. private static Object getRowColumn(JetFormat format,
  582. ByteBuffer rowBuffer,
  583. Column column,
  584. RowState rowState,
  585. Map<Column,byte[]> rawVarValues)
  586. throws IOException
  587. {
  588. byte[] columnData = null;
  589. try {
  590. NullMask nullMask = rowState.getNullMask(rowBuffer);
  591. boolean isNull = nullMask.isNull(column);
  592. if(column.getType() == DataType.BOOLEAN) {
  593. // Boolean values are stored in the null mask. see note about
  594. // caching below
  595. return rowState.setRowValue(column.getColumnIndex(),
  596. Boolean.valueOf(!isNull));
  597. } else if(isNull) {
  598. // well, that's easy! (no need to update cache w/ null)
  599. return null;
  600. }
  601. // reset position to row start
  602. rowBuffer.reset();
  603. // locate the column data bytes
  604. int rowStart = rowBuffer.position();
  605. int colDataPos = 0;
  606. int colDataLen = 0;
  607. if(!column.isVariableLength()) {
  608. // read fixed length value (non-boolean at this point)
  609. int dataStart = rowStart + format.OFFSET_COLUMN_FIXED_DATA_ROW_OFFSET;
  610. colDataPos = dataStart + column.getFixedDataOffset();
  611. colDataLen = column.getType().getFixedSize(column.getLength());
  612. } else {
  613. int varDataStart;
  614. int varDataEnd;
  615. if(format.SIZE_ROW_VAR_COL_OFFSET == 2) {
  616. // read simple var length value
  617. int varColumnOffsetPos =
  618. (rowBuffer.limit() - nullMask.byteSize() - 4) -
  619. (column.getVarLenTableIndex() * 2);
  620. varDataStart = rowBuffer.getShort(varColumnOffsetPos);
  621. varDataEnd = rowBuffer.getShort(varColumnOffsetPos - 2);
  622. } else {
  623. // read jump-table based var length values
  624. short[] varColumnOffsets = readJumpTableVarColOffsets(
  625. rowState, rowBuffer, rowStart, nullMask);
  626. varDataStart = varColumnOffsets[column.getVarLenTableIndex()];
  627. varDataEnd = varColumnOffsets[column.getVarLenTableIndex() + 1];
  628. }
  629. colDataPos = rowStart + varDataStart;
  630. colDataLen = varDataEnd - varDataStart;
  631. }
  632. // grab the column data
  633. columnData = new byte[colDataLen];
  634. rowBuffer.position(colDataPos);
  635. rowBuffer.get(columnData);
  636. if((rawVarValues != null) && column.isVariableLength()) {
  637. // caller wants raw value as well
  638. rawVarValues.put(column, columnData);
  639. }
  640. // parse the column data. we cache the row values in order to be able
  641. // to update the index on row deletion. note, most of the returned
  642. // values are immutable, except for binary data (returned as byte[]),
  643. // but binary data shouldn't be indexed anyway.
  644. return rowState.setRowValue(column.getColumnIndex(),
  645. column.read(columnData));
  646. } catch(Exception e) {
  647. // cache "raw" row value. see note about caching above
  648. rowState.setRowValue(column.getColumnIndex(),
  649. Column.rawDataWrapper(columnData));
  650. return rowState.handleRowError(column, columnData, e);
  651. }
  652. }
  653. private static short[] readJumpTableVarColOffsets(
  654. RowState rowState, ByteBuffer rowBuffer, int rowStart,
  655. NullMask nullMask)
  656. {
  657. short[] varColOffsets = rowState.getVarColOffsets();
  658. if(varColOffsets != null) {
  659. return varColOffsets;
  660. }
  661. // calculate offsets using jump-table info
  662. int nullMaskSize = nullMask.byteSize();
  663. int rowEnd = rowStart + rowBuffer.remaining() - 1;
  664. int numVarCols = ByteUtil.getUnsignedByte(rowBuffer,
  665. rowEnd - nullMaskSize);
  666. varColOffsets = new short[numVarCols + 1];
  667. int rowLen = rowEnd - rowStart + 1;
  668. int numJumps = (rowLen - 1) / MAX_BYTE;
  669. int colOffset = rowEnd - nullMaskSize - numJumps - 1;
  670. // If last jump is a dummy value, ignore it
  671. if(((colOffset - rowStart - numVarCols) / MAX_BYTE) < numJumps) {
  672. numJumps--;
  673. }
  674. int jumpsUsed = 0;
  675. for(int i = 0; i < numVarCols + 1; i++) {
  676. while((jumpsUsed < numJumps) &&
  677. (i == ByteUtil.getUnsignedByte(
  678. rowBuffer, rowEnd - nullMaskSize-jumpsUsed - 1))) {
  679. jumpsUsed++;
  680. }
  681. varColOffsets[i] = (short)
  682. (ByteUtil.getUnsignedByte(rowBuffer, colOffset - i)
  683. + (jumpsUsed * MAX_BYTE));
  684. }
  685. rowState.setVarColOffsets(varColOffsets);
  686. return varColOffsets;
  687. }
  688. /**
  689. * Reads the null mask from the given row buffer. Leaves limit unchanged.
  690. */
  691. private NullMask getRowNullMask(ByteBuffer rowBuffer)
  692. throws IOException
  693. {
  694. // reset position to row start
  695. rowBuffer.reset();
  696. // Number of columns in this row
  697. int columnCount = ByteUtil.getUnsignedVarInt(
  698. rowBuffer, getFormat().SIZE_ROW_COLUMN_COUNT);
  699. // read null mask
  700. NullMask nullMask = new NullMask(columnCount);
  701. rowBuffer.position(rowBuffer.limit() - nullMask.byteSize()); //Null mask at end
  702. nullMask.read(rowBuffer);
  703. return nullMask;
  704. }
  705. /**
  706. * Sets a new buffer to the correct row header page using the given rowState
  707. * according to the given rowId. Deleted state is
  708. * determined, but overflow row pointers are not followed.
  709. *
  710. * @return a ByteBuffer of the relevant page, or null if row was invalid
  711. * @usage _advanced_method_
  712. */
  713. public static ByteBuffer positionAtRowHeader(RowState rowState, RowId rowId)
  714. throws IOException
  715. {
  716. ByteBuffer rowBuffer = rowState.setHeaderRow(rowId);
  717. if(rowState.isAtHeaderRow()) {
  718. // this task has already been accomplished
  719. return rowBuffer;
  720. }
  721. if(!rowState.isValid()) {
  722. // this was an invalid page/row
  723. rowState.setStatus(RowStateStatus.AT_HEADER);
  724. return null;
  725. }
  726. // note, we don't use findRowStart here cause we need the unmasked value
  727. short rowStart = rowBuffer.getShort(
  728. getRowStartOffset(rowId.getRowNumber(),
  729. rowState.getTable().getFormat()));
  730. // check the deleted, overflow flags for the row (the "real" flags are
  731. // always set on the header row)
  732. RowStatus rowStatus = RowStatus.NORMAL;
  733. if(isDeletedRow(rowStart)) {
  734. rowStatus = RowStatus.DELETED;
  735. } else if(isOverflowRow(rowStart)) {
  736. rowStatus = RowStatus.OVERFLOW;
  737. }
  738. rowState.setRowStatus(rowStatus);
  739. rowState.setStatus(RowStateStatus.AT_HEADER);
  740. return rowBuffer;
  741. }
  742. /**
  743. * Sets the position and limit in a new buffer using the given rowState
  744. * according to the given row number and row end, following overflow row
  745. * pointers as necessary.
  746. *
  747. * @return a ByteBuffer narrowed to the actual row data, or null if row was
  748. * invalid or deleted
  749. * @usage _advanced_method_
  750. */
  751. public static ByteBuffer positionAtRowData(RowState rowState, RowId rowId)
  752. throws IOException
  753. {
  754. positionAtRowHeader(rowState, rowId);
  755. if(!rowState.isValid() || rowState.isDeleted()) {
  756. // row is invalid or deleted
  757. rowState.setStatus(RowStateStatus.AT_FINAL);
  758. return null;
  759. }
  760. ByteBuffer rowBuffer = rowState.getFinalPage();
  761. int rowNum = rowState.getFinalRowId().getRowNumber();
  762. JetFormat format = rowState.getTable().getFormat();
  763. if(rowState.isAtFinalRow()) {
  764. // we've already found the final row data
  765. return PageChannel.narrowBuffer(
  766. rowBuffer,
  767. findRowStart(rowBuffer, rowNum, format),
  768. findRowEnd(rowBuffer, rowNum, format));
  769. }
  770. while(true) {
  771. // note, we don't use findRowStart here cause we need the unmasked value
  772. short rowStart = rowBuffer.getShort(getRowStartOffset(rowNum, format));
  773. short rowEnd = findRowEnd(rowBuffer, rowNum, format);
  774. // note, at this point we know the row is not deleted, so ignore any
  775. // subsequent deleted flags (as overflow rows are always marked deleted
  776. // anyway)
  777. boolean overflowRow = isOverflowRow(rowStart);
  778. // now, strip flags from rowStart offset
  779. rowStart = (short)(rowStart & OFFSET_MASK);
  780. if (overflowRow) {
  781. if((rowEnd - rowStart) < 4) {
  782. throw new IOException("invalid overflow row info");
  783. }
  784. // Overflow page. the "row" data in the current page points to
  785. // another page/row
  786. int overflowRowNum = ByteUtil.getUnsignedByte(rowBuffer, rowStart);
  787. int overflowPageNum = ByteUtil.get3ByteInt(rowBuffer, rowStart + 1);
  788. rowBuffer = rowState.setOverflowRow(
  789. new RowId(overflowPageNum, overflowRowNum));
  790. rowNum = overflowRowNum;
  791. } else {
  792. rowState.setStatus(RowStateStatus.AT_FINAL);
  793. return PageChannel.narrowBuffer(rowBuffer, rowStart, rowEnd);
  794. }
  795. }
  796. }
  797. /**
  798. * Calls <code>reset</code> on this table and returns a modifiable
  799. * Iterator which will iterate through all the rows of this table. Use of
  800. * the Iterator follows the same restrictions as a call to
  801. * <code>getNextRow</code>.
  802. * @throws IllegalStateException if an IOException is thrown by one of the
  803. * operations, the actual exception will be contained within
  804. * @usage _general_method_
  805. */
  806. public Iterator<Map<String, Object>> iterator()
  807. {
  808. return iterator(null);
  809. }
  810. /**
  811. * Calls <code>reset</code> on this table and returns a modifiable
  812. * Iterator which will iterate through all the rows of this table, returning
  813. * only the given columns. Use of the Iterator follows the same
  814. * restrictions as a call to <code>getNextRow</code>.
  815. * @throws IllegalStateException if an IOException is thrown by one of the
  816. * operations, the actual exception will be contained within
  817. * @usage _general_method_
  818. */
  819. public Iterator<Map<String, Object>> iterator(Collection<String> columnNames)
  820. {
  821. reset();
  822. return getInternalCursor().iterator(columnNames);
  823. }
  824. /**
  825. * Writes a new table defined by the given columns and indexes to the
  826. * database.
  827. * @return the first page of the new table's definition
  828. * @usage _advanced_method_
  829. */
  830. public static int writeTableDefinition(
  831. List<Column> columns, List<IndexBuilder> indexes,
  832. PageChannel pageChannel, JetFormat format, Charset charset)
  833. throws IOException
  834. {
  835. int indexCount = 0;
  836. int logicalIndexCount = 0;
  837. if(!indexes.isEmpty()) {
  838. // sort out index numbers. for now, these values will always match
  839. // (until we support writing foreign key indexes)
  840. for(IndexBuilder idx : indexes) {
  841. idx.setIndexNumber(logicalIndexCount++);
  842. idx.setIndexDataNumber(indexCount++);
  843. }
  844. }
  845. // allocate first table def page
  846. int tdefPageNumber = pageChannel.allocateNewPage();
  847. // first, create the usage map page
  848. int usageMapPageNumber =
  849. createUsageMapDefinitionBuffer(indexes, pageChannel, format);
  850. // next, determine how big the table def will be (in case it will be more
  851. // than one page)
  852. int idxDataLen = (indexCount * (format.SIZE_INDEX_DEFINITION +
  853. format.SIZE_INDEX_COLUMN_BLOCK)) +
  854. (logicalIndexCount * format.SIZE_INDEX_INFO_BLOCK);
  855. int totalTableDefSize = format.SIZE_TDEF_HEADER +
  856. (format.SIZE_COLUMN_DEF_BLOCK * columns.size()) + idxDataLen +
  857. format.SIZE_TDEF_TRAILER;
  858. // total up the amount of space used by the column and index names (2
  859. // bytes per char + 2 bytes for the length)
  860. for(Column col : columns) {
  861. int nameByteLen = (col.getName().length() *
  862. JetFormat.TEXT_FIELD_UNIT_SIZE);
  863. totalTableDefSize += nameByteLen + 2;
  864. }
  865. for(IndexBuilder idx : indexes) {
  866. int nameByteLen = (idx.getName().length() *
  867. JetFormat.TEXT_FIELD_UNIT_SIZE);
  868. totalTableDefSize += nameByteLen + 2;
  869. }
  870. // now, create the table definition
  871. ByteBuffer buffer = pageChannel.createBuffer(Math.max(totalTableDefSize,
  872. format.PAGE_SIZE));
  873. writeTableDefinitionHeader(buffer, columns, usageMapPageNumber,
  874. totalTableDefSize, indexCount,
  875. logicalIndexCount, format);
  876. if(indexCount > 0) {
  877. // index row counts
  878. IndexData.writeRowCountDefinitions(buffer, indexCount, format);
  879. }
  880. // column definitions
  881. Column.writeDefinitions(buffer, columns, format, charset);
  882. if(indexCount > 0) {
  883. // index and index data definitions
  884. IndexData.writeDefinitions(buffer, columns, indexes, tdefPageNumber,
  885. pageChannel, format);
  886. Index.writeDefinitions(buffer, indexes, charset);
  887. }
  888. //End of tabledef
  889. buffer.put((byte) 0xff);
  890. buffer.put((byte) 0xff);
  891. // write table buffer to database
  892. if(totalTableDefSize <= format.PAGE_SIZE) {
  893. // easy case, fits on one page
  894. buffer.putShort(format.OFFSET_FREE_SPACE,
  895. (short)(buffer.remaining() - 8)); // overwrite page free space
  896. // Write the tdef page to disk.
  897. pageChannel.writePage(buffer, tdefPageNumber);
  898. } else {
  899. // need to split across multiple pages
  900. ByteBuffer partialTdef = pageChannel.createPageBuffer();
  901. buffer.rewind();
  902. int nextTdefPageNumber = PageChannel.INVALID_PAGE_NUMBER;
  903. while(buffer.hasRemaining()) {
  904. // reset for next write
  905. partialTdef.clear();
  906. if(nextTdefPageNumber == PageChannel.INVALID_PAGE_NUMBER) {
  907. // this is the first page. note, the first page already has the
  908. // page header, so no need to write it here
  909. nextTdefPageNumber = tdefPageNumber;
  910. } else {
  911. // write page header
  912. writeTablePageHeader(partialTdef);
  913. }
  914. // copy the next page of tdef bytes
  915. int curTdefPageNumber = nextTdefPageNumber;
  916. int writeLen = Math.min(partialTdef.remaining(), buffer.remaining());
  917. partialTdef.put(buffer.array(), buffer.position(), writeLen);
  918. ByteUtil.forward(buffer, writeLen);
  919. if(buffer.hasRemaining()) {
  920. // need a next page
  921. nextTdefPageNumber = pageChannel.allocateNewPage();
  922. partialTdef.putInt(format.OFFSET_NEXT_TABLE_DEF_PAGE,
  923. nextTdefPageNumber);
  924. }
  925. // update page free space
  926. partialTdef.putShort(format.OFFSET_FREE_SPACE,
  927. (short)(partialTdef.remaining() - 8)); // overwrite page free space
  928. // write partial page to disk
  929. pageChannel.writePage(partialTdef, curTdefPageNumber);
  930. }
  931. }
  932. return tdefPageNumber;
  933. }
  934. /**
  935. * @param buffer Buffer to write to
  936. * @param columns List of Columns in the table
  937. */
  938. private static void writeTableDefinitionHeader(
  939. ByteBuffer buffer, List<Column> columns,
  940. int usageMapPageNumber, int totalTableDefSize,
  941. int indexCount, int logicalIndexCount, JetFormat format)
  942. throws IOException
  943. {
  944. //Start writing the tdef
  945. writeTablePageHeader(buffer);
  946. buffer.putInt(totalTableDefSize); //Length of table def
  947. buffer.putInt(MAGIC_TABLE_NUMBER); // seemingly constant magic value
  948. buffer.putInt(0); //Number of rows
  949. buffer.putInt(0); //Last Autonumber
  950. buffer.put((byte) 1); // this makes autonumbering work in access
  951. for (int i = 0; i < 15; i++) { //Unknown
  952. buffer.put((byte) 0);
  953. }
  954. buffer.put(Table.TYPE_USER); //Table type
  955. buffer.putShort((short) columns.size()); //Max columns a row will have
  956. buffer.putShort(Column.countVariableLength(columns)); //Number of variable columns in table
  957. buffer.putShort((short) columns.size()); //Number of columns in table
  958. buffer.putInt(logicalIndexCount); //Number of logical indexes in table
  959. buffer.putInt(indexCount); //Number of indexes in table
  960. buffer.put((byte) 0); //Usage map row number
  961. ByteUtil.put3ByteInt(buffer, usageMapPageNumber); //Usage map page number
  962. buffer.put((byte) 1); //Free map row number
  963. ByteUtil.put3ByteInt(buffer, usageMapPageNumber); //Free map page number
  964. if (LOG.isDebugEnabled()) {
  965. int position = buffer.position();
  966. buffer.rewind();
  967. LOG.debug("Creating new table def block:\n" + ByteUtil.toHexString(
  968. buffer, format.SIZE_TDEF_HEADER));
  969. buffer.position(position);
  970. }
  971. }
  972. /**
  973. * Writes the page header for a table definition page
  974. * @param buffer Buffer to write to
  975. */
  976. private static void writeTablePageHeader(ByteBuffer buffer)
  977. {
  978. buffer.put(PageTypes.TABLE_DEF); //Page type
  979. buffer.put((byte) 0x01); //Unknown
  980. buffer.put((byte) 0); //Unknown
  981. buffer.put((byte) 0); //Unknown
  982. buffer.putInt(0); //Next TDEF page pointer
  983. }
  984. /**
  985. * Writes the given name into the given buffer in the format as expected by
  986. * {@link #readName}.
  987. */
  988. static void writeName(ByteBuffer buffer, String name, Charset charset)
  989. {
  990. ByteBuffer encName = Column.encodeUncompressedText(name, charset);
  991. buffer.putShort((short) encName.remaining());
  992. buffer.put(encName);
  993. }
  994. /**
  995. * Create the usage map definition page buffer. The "used pages" map is in
  996. * row 0, the "pages with free space" map is in row 1. Index usage maps are
  997. * in subsequent rows.
  998. */
  999. private static int createUsageMapDefinitionBuffer(
  1000. List<IndexBuilder> indexes, PageChannel pageChannel, JetFormat format)
  1001. throws IOException
  1002. {
  1003. // 2 table usage maps plus 1 for each index
  1004. int umapNum = 2 + indexes.size();
  1005. int usageMapRowLength = format.OFFSET_USAGE_MAP_START +
  1006. format.USAGE_MAP_TABLE_BYTE_LENGTH;
  1007. int freeSpace = format.DATA_PAGE_INITIAL_FREE_SPACE
  1008. - (umapNum * getRowSpaceUsage(usageMapRowLength, format));
  1009. // for now, don't handle writing that many indexes
  1010. if(freeSpace < 0) {
  1011. throw new IOException("FIXME attempting to write too many indexes");
  1012. }
  1013. int umapPageNumber = pageChannel.allocateNewPage();
  1014. ByteBuffer rtn = pageChannel.createPageBuffer();
  1015. rtn.put(PageTypes.DATA);
  1016. rtn.put((byte) 0x1); //Unknown
  1017. rtn.putShort((short)freeSpace); //Free space in page
  1018. rtn.putInt(0); //Table definition
  1019. rtn.putInt(0); //Unknown
  1020. rtn.putShort((short) umapNum); //Number of records on this page
  1021. // write two rows of usage map definitions for the table
  1022. int rowStart = findRowEnd(rtn, 0, format) - usageMapRowLength;
  1023. for(int i = 0; i < 2; ++i) {
  1024. rtn.putShort(getRowStartOffset(i, format), (short)rowStart);
  1025. if(i == 0) {
  1026. // initial "usage pages" map definition
  1027. rtn.put(rowStart, UsageMap.MAP_TYPE_REFERENCE);
  1028. } else {
  1029. // initial "pages with free space" map definition
  1030. rtn.put(rowStart, UsageMap.MAP_TYPE_INLINE);
  1031. }
  1032. rowStart -= usageMapRowLength;
  1033. }
  1034. if(!indexes.isEmpty()) {
  1035. for(int i = 0; i < indexes.size(); ++i) {
  1036. IndexBuilder idx = indexes.get(i);
  1037. // allocate root page for the index
  1038. int rootPageNumber = pageChannel.allocateNewPage();
  1039. int umapRowNum = i + 2;
  1040. // stash info for later use
  1041. idx.setRootPageNumber(rootPageNumber);
  1042. idx.setUmapRowNumber((byte)umapRowNum);
  1043. idx.setUmapPageNumber(umapPageNumber);
  1044. // index map definition, including initial root page
  1045. rtn.putShort(getRowStartOffset(umapRowNum, format), (short)rowStart);
  1046. rtn.put(rowStart, UsageMap.MAP_TYPE_INLINE);
  1047. rtn.putInt(rowStart + 1, rootPageNumber);
  1048. rtn.put(rowStart + 5, (byte)1);
  1049. rowStart -= usageMapRowLength;
  1050. }
  1051. }
  1052. pageChannel.writePage(rtn, umapPageNumber);
  1053. return umapPageNumber;
  1054. }
  1055. /**
  1056. * Read the table definition
  1057. */
  1058. private void readTableDefinition(ByteBuffer tableBuffer) throws IOException
  1059. {
  1060. if (LOG.isDebugEnabled()) {
  1061. tableBuffer.rewind();
  1062. LOG.debug("Table def block:\n" + ByteUtil.toHexString(tableBuffer,
  1063. getFormat().SIZE_TDEF_HEADER));
  1064. }
  1065. _rowCount = tableBuffer.getInt(getFormat().OFFSET_NUM_ROWS);
  1066. _lastLongAutoNumber = tableBuffer.getInt(getFormat().OFFSET_NEXT_AUTO_NUMBER);
  1067. if(getFormat().OFFSET_NEXT_COMPLEX_AUTO_NUMBER >= 0) {
  1068. _lastComplexTypeAutoNumber = tableBuffer.getInt(
  1069. getFormat().OFFSET_NEXT_COMPLEX_AUTO_NUMBER);
  1070. }
  1071. _tableType = tableBuffer.get(getFormat().OFFSET_TABLE_TYPE);
  1072. _maxColumnCount = tableBuffer.getShort(getFormat().OFFSET_MAX_COLS);
  1073. _maxVarColumnCount = tableBuffer.getShort(getFormat().OFFSET_NUM_VAR_COLS);
  1074. short columnCount = tableBuffer.getShort(getFormat().OFFSET_NUM_COLS);
  1075. _logicalIndexCount = tableBuffer.getInt(getFormat().OFFSET_NUM_INDEX_SLOTS);
  1076. _indexCount = tableBuffer.getInt(getFormat().OFFSET_NUM_INDEXES);
  1077. int rowNum = ByteUtil.getUnsignedByte(
  1078. tableBuffer, getFormat().OFFSET_OWNED_PAGES);
  1079. int pageNum = ByteUtil.get3ByteInt(tableBuffer, getFormat().OFFSET_OWNED_PAGES + 1);
  1080. _ownedPages = UsageMap.read(getDatabase(), pageNum, rowNum, false);
  1081. rowNum = ByteUtil.getUnsignedByte(
  1082. tableBuffer, getFormat().OFFSET_FREE_SPACE_PAGES);
  1083. pageNum = ByteUtil.get3ByteInt(tableBuffer, getFormat().OFFSET_FREE_SPACE_PAGES + 1);
  1084. _freeSpacePages = UsageMap.read(getDatabase(), pageNum, rowNum, false);
  1085. for (int i = 0; i < _indexCount; i++) {
  1086. _indexDatas.add(IndexData.create(this, tableBuffer, i, getFormat()));
  1087. }
  1088. int colOffset = getFormat().OFFSET_INDEX_DEF_BLOCK +
  1089. _indexCount * getFormat().SIZE_INDEX_DEFINITION;
  1090. int dispIndex = 0;
  1091. for (int i = 0; i < columnCount; i++) {
  1092. Column column = new Column(this, tableBuffer,
  1093. colOffset + (i * getFormat().SIZE_COLUMN_HEADER), dispIndex++);
  1094. _columns.add(column);
  1095. if(column.isVariableLength()) {
  1096. // also shove it in the variable columns list, which is ordered
  1097. // differently from the _columns list
  1098. _varColumns.add(column);
  1099. }
  1100. }
  1101. tableBuffer.position(colOffset +
  1102. (columnCount * getFormat().SIZE_COLUMN_HEADER));
  1103. for (int i = 0; i < columnCount; i++) {
  1104. Column column = _columns.get(i);
  1105. column.setName(readName(tableBuffer));
  1106. }
  1107. Collections.sort(_columns);
  1108. _autoNumColumns = getAutoNumberColumns(_columns);
  1109. // setup the data index for the columns
  1110. int colIdx = 0;
  1111. for(Column col : _columns) {
  1112. col.setColumnIndex(colIdx++);
  1113. }
  1114. // sort variable length columns based on their index into the variable
  1115. // length offset table, because we will write the columns in this order
  1116. Collections.sort(_varColumns, VAR_LEN_COLUMN_COMPARATOR);
  1117. // read index column information
  1118. for (int i = 0; i < _indexCount; i++) {
  1119. _indexDatas.get(i).read(tableBuffer, _columns);
  1120. }
  1121. // read logical index info (may be more logical indexes than index datas)
  1122. for (int i = 0; i < _logicalIndexCount; i++) {
  1123. _indexes.add(new Index(tableBuffer, _indexDatas, getFormat()));
  1124. }
  1125. // read logical index names
  1126. for (int i = 0; i < _logicalIndexCount; i++) {
  1127. _indexes.get(i).setName(readName(tableBuffer));
  1128. }
  1129. Collections.sort(_indexes);
  1130. // re-sort columns if necessary
  1131. if(getDatabase().getColumnOrder() != ColumnOrder.DATA) {
  1132. Collections.sort(_columns, DISPLAY_ORDER_COMPARATOR);
  1133. }
  1134. for(Column col : _columns) {
  1135. // some columns need to do extra work after the table is completely
  1136. // loaded
  1137. col.postTableLoadInit();
  1138. }
  1139. }
  1140. /**
  1141. * Writes the given page data to the given page number, clears any other
  1142. * relevant buffers.
  1143. */
  1144. private void writeDataPage(ByteBuffer pageBuffer, int pageNumber)
  1145. throws IOException
  1146. {
  1147. // write the page data
  1148. getPageChannel().writePage(pageBuffer, pageNumber);
  1149. // possibly invalidate the add row buffer if a different data buffer is
  1150. // being written (e.g. this happens during deleteRow)
  1151. _addRowBufferH.possiblyInvalidate(pageNumber, pageBuffer);
  1152. // update modification count so any active RowStates can keep themselves
  1153. // up-to-date
  1154. ++_modCount;
  1155. }
  1156. /**
  1157. * Returns a name read from the buffer at the current position. The
  1158. * expected name format is the name length followed by the name
  1159. * encoded using the {@link JetFormat#CHARSET}
  1160. */
  1161. private String readName(ByteBuffer buffer) {
  1162. int nameLength = readNameLength(buffer);
  1163. byte[] nameBytes = new byte[nameLength];
  1164. buffer.get(nameBytes);
  1165. return Column.decodeUncompressedText(nameBytes,
  1166. getDatabase().getCharset());
  1167. }
  1168. /**
  1169. * Returns a name length read from the buffer at the current position.
  1170. */
  1171. private int readNameLength(ByteBuffer buffer) {
  1172. return ByteUtil.getUnsignedVarInt(buffer, getFormat().SIZE_NAME_LENGTH);
  1173. }
  1174. /**
  1175. * Converts a map of columnName -> columnValue to an array of row values
  1176. * appropriate for a call to {@link #addRow(Object...)}.
  1177. * @usage _general_method_
  1178. */
  1179. public Object[] asRow(Map<String,Object> rowMap) {
  1180. return asRow(rowMap, null);
  1181. }
  1182. /**
  1183. * Converts a map of columnName -> columnValue to an array of row values
  1184. * appropriate for a call to {@link #updateCurrentRow(Object...)}.
  1185. * @usage _general_method_
  1186. */
  1187. public Object[] asUpdateRow(Map<String,Object> rowMap) {
  1188. return asRow(rowMap, Column.KEEP_VALUE);
  1189. }
  1190. /**
  1191. * Converts a map of columnName -> columnValue to an array of row values.
  1192. */
  1193. private Object[] asRow(Map<String,Object> rowMap, Object defaultValue)
  1194. {
  1195. Object[] row = new Object[_columns.size()];
  1196. if(defaultValue != null) {
  1197. Arrays.fill(row, defaultValue);
  1198. }
  1199. if(rowMap == null) {
  1200. return row;
  1201. }
  1202. for(Column col : _columns) {
  1203. if(rowMap.containsKey(col.getName())) {
  1204. col.setRowValue(row, col.getRowValue(rowMap));
  1205. }
  1206. }
  1207. return row;
  1208. }
  1209. /**
  1210. * Add a single row to this table and write it to disk
  1211. * <p>
  1212. * Note, if this table has an auto-number column, the value written will be
  1213. * put back into the given row array.
  1214. *
  1215. * @param row row values for a single row. the row will be modified if
  1216. * this table contains an auto-number column, otherwise it
  1217. * will not be modified.
  1218. * @usage _general_method_
  1219. */
  1220. public void addRow(Object... row) throws IOException {
  1221. addRows(Collections.singletonList(row), _singleRowBufferH);
  1222. }
  1223. /**
  1224. * Add multiple rows to this table, only writing to disk after all
  1225. * rows have been written, and every time a data page is filled. This
  1226. * is much more efficient than calling <code>addRow</code> multiple times.
  1227. * <p>
  1228. * Note, if this table has an auto-number column, the values written will be
  1229. * put back into the given row arrays.
  1230. *
  1231. * @param rows List of Object[] row values. the rows will be modified if
  1232. * this table contains an auto-number column, otherwise they
  1233. * will not be modified.
  1234. * @usage _general_method_
  1235. */
  1236. public void addRows(List<? extends Object[]> rows) throws IOException {
  1237. addRows(rows, _multiRowBufferH);
  1238. }
  1239. /**
  1240. * Add multiple rows to this table, only writing to disk after all
  1241. * rows have been written, and every time a data page is filled.
  1242. * @param inRows List of Object[] row values
  1243. * @param writeRowBufferH TempBufferHolder used to generate buffers for
  1244. * writing the row data
  1245. */
  1246. private void addRows(List<? extends Object[]> inRows,
  1247. TempBufferHolder writeRowBufferH)
  1248. throws IOException
  1249. {
  1250. if(inRows.isEmpty()) {
  1251. return;
  1252. }
  1253. // copy the input rows to a modifiable list so we can update the elements
  1254. List<Object[]> rows = new ArrayList<Object[]>(inRows);
  1255. ByteBuffer[] rowData = new ByteBuffer[rows.size()];
  1256. for (int i = 0; i < rows.size(); i++) {
  1257. // we need to make sure the row is the right length (fill with null).
  1258. // note, if the row is copied the caller will not be able to access any
  1259. // generated auto-number value, but if they need that info they should
  1260. // use a row array of the right size!
  1261. Object[] row = rows.get(i);
  1262. if(row.length < _columns.size()) {
  1263. row = dupeRow(row, _columns.size());
  1264. // we copied the row, so put the copy back into the rows list
  1265. rows.set(i, row);
  1266. }
  1267. // fill in autonumbers
  1268. handleAutoNumbersForAdd(row);
  1269. // write the row of data to a temporary buffer
  1270. rowData[i] = createRow(row, writeRowBufferH.getPageBuffer(getPageChannel()));
  1271. if (rowData[i].limit() > getFormat().MAX_ROW_SIZE) {
  1272. throw new IOException("Row size " + rowData[i].limit() +
  1273. " is too large");
  1274. }
  1275. }
  1276. ByteBuffer dataPage = null;
  1277. int pageNumber = PageChannel.INVALID_PAGE_NUMBER;
  1278. for (int i = 0; i < rowData.length; i++) {
  1279. int rowSize = rowData[i].remaining();
  1280. // get page with space
  1281. dataPage = findFreeRowSpace(rowSize, dataPage, pageNumber);
  1282. pageNumber = _addRowBufferH.getPageNumber();
  1283. // write out the row data
  1284. int rowNum = addDataPageRow(dataPage, rowSize, getFormat(), 0);
  1285. dataPage.put(rowData[i]);
  1286. // update the indexes
  1287. RowId rowId = new RowId(pageNumber, rowNum);
  1288. for(IndexData indexData : _indexDatas) {
  1289. indexData.addRow(rows.get(i), rowId);
  1290. }
  1291. }
  1292. writeDataPage(dataPage, pageNumber);
  1293. // Update tdef page
  1294. updateTableDefinition(rows.size());
  1295. }
  1296. /**
  1297. * Updates the current row to the new values.
  1298. * <p>
  1299. * Note, if this table has an auto-number column(s), the existing value(s)
  1300. * will be maintained, unchanged.
  1301. *
  1302. * @param row new row values for the current row.
  1303. * @usage _general_method_
  1304. */
  1305. public void updateCurrentRow(Object... row) throws IOException {
  1306. getInternalCursor().updateCurrentRow(row);
  1307. }
  1308. /**
  1309. * Update the row on which the given rowState is currently positioned.
  1310. * <p>
  1311. * Note, this method is not generally meant to be used directly. You should
  1312. * use the {@link #updateCurrentRow} method or use the Cursor class, which
  1313. * allows for more complex table interactions, e.g.
  1314. * {@link Cursor#setCurrentRowValue} and {@link Cursor#updateCurrentRow}.
  1315. * @usage _advanced_method_
  1316. */
  1317. public void updateRow(RowState rowState, RowId rowId, Object... row)
  1318. throws IOException
  1319. {
  1320. requireValidRowId(rowId);
  1321. // ensure that the relevant row state is up-to-date
  1322. ByteBuffer rowBuffer = positionAtRowData(rowState, rowId);
  1323. int oldRowSize = rowBuffer.remaining();
  1324. requireNonDeletedRow(rowState, rowId);
  1325. // we need to make sure the row is the right length (fill with null).
  1326. if(row.length < _columns.size()) {
  1327. row = dupeRow(row, _columns.size());
  1328. }
  1329. // fill in any auto-numbers (we don't allow autonumber values to be
  1330. // modified)
  1331. handleAutoNumbersForUpdate(row, rowBuffer, rowState);
  1332. // hang on to the raw values of var length columns we are "keeping". this
  1333. // will allow us to re-use pre-written var length data, which can save
  1334. // space for things like long value columns.
  1335. Map<Column,byte[]> rawVarValues =
  1336. (!_varColumns.isEmpty() ? new HashMap<Column,byte[]>() : null);
  1337. // fill in any "keep value" fields
  1338. for(Column column : _columns) {
  1339. if(column.getRowValue(row) == Column.KEEP_VALUE) {
  1340. column.setRowValue(
  1341. row, getRowColumn(getFormat(), rowBuffer, column, rowState,
  1342. rawVarValues));
  1343. }
  1344. }
  1345. // generate new row bytes
  1346. ByteBuffer newRowData = createRow(
  1347. row, _singleRowBufferH.getPageBuffer(getPageChannel()), oldRowSize,
  1348. rawVarValues);
  1349. if (newRowData.limit() > getFormat().MAX_ROW_SIZE) {
  1350. throw new IOException("Row size " + newRowData.limit() +
  1351. " is too large");
  1352. }
  1353. if(!_indexDatas.isEmpty()) {
  1354. Object[] oldRowValues = rowState.getRowValues();
  1355. // delete old values from indexes
  1356. for(IndexData indexData : _indexDatas) {
  1357. indexData.deleteRow(oldRowValues, rowId);
  1358. }
  1359. }
  1360. // see if we can squeeze the new row data into the existing row
  1361. rowBuffer.reset();
  1362. int rowSize = newRowData.remaining();
  1363. ByteBuffer dataPage = null;
  1364. int pageNumber = PageChannel.INVALID_PAGE_NUMBER;
  1365. if(oldRowSize >= rowSize) {
  1366. // awesome, slap it in!
  1367. rowBuffer.put(newRowData);
  1368. // grab the page we just updated
  1369. dataPage = rowState.getFinalPage();
  1370. pageNumber = rowState.getFinalRowId().getPageNumber();
  1371. } else {
  1372. // bummer, need to find a new page for the data
  1373. dataPage = findFreeRowSpace(rowSize, null,
  1374. PageChannel.INVALID_PAGE_NUMBER);
  1375. pageNumber = _addRowBufferH.getPageNumber();
  1376. RowId headerRowId = rowState.getHeaderRowId();
  1377. ByteBuffer headerPage = rowState.getHeaderPage();
  1378. if(pageNumber == headerRowId.getPageNumber()) {
  1379. // new row is on the same page as header row, share page
  1380. dataPage = headerPage;
  1381. }
  1382. // write out the new row data (set the deleted flag on the new data row
  1383. // so that it is ignored during normal table traversal)
  1384. int rowNum = addDataPageRow(dataPage, rowSize, getFormat(),
  1385. DELETED_ROW_MASK);
  1386. dataPage.put(newRowData);
  1387. // write the overflow info into the header row and clear out the
  1388. // remaining header data
  1389. rowBuffer = PageChannel.narrowBuffer(
  1390. headerPage,
  1391. findRowStart(headerPage, headerRowId.getRowNumber(), getFormat()),
  1392. findRowEnd(headerPage, headerRowId.getRowNumber(), getFormat()));
  1393. rowBuffer.put((byte)rowNum);
  1394. ByteUtil.put3ByteInt(rowBuffer, pageNumber);
  1395. ByteUtil.clearRemaining(rowBuffer);
  1396. // set the overflow flag on the header row
  1397. int headerRowIndex = getRowStartOffset(headerRowId.getRowNumber(),
  1398. getFormat());
  1399. headerPage.putShort(headerRowIndex,
  1400. (short)(headerPage.getShort(headerRowIndex)
  1401. | OVERFLOW_ROW_MASK));
  1402. if(pageNumber != headerRowId.getPageNumber()) {
  1403. writeDataPage(headerPage, headerRowId.getPageNumber());
  1404. }
  1405. }
  1406. // update the indexes
  1407. for(IndexData indexData : _indexDatas) {
  1408. indexData.addRow(row, rowId);
  1409. }
  1410. writeDataPage(dataPage, pageNumber);
  1411. updateTableDefinition(0);
  1412. }
  1413. private ByteBuffer findFreeRowSpace(int rowSize, ByteBuffer dataPage,
  1414. int pageNumber)
  1415. throws IOException
  1416. {
  1417. if(dataPage == null) {
  1418. // find last data page (Not bothering to check other pages for free
  1419. // space.)
  1420. UsageMap.PageCursor revPageCursor = _ownedPages.cursor();
  1421. revPageCursor.afterLast();
  1422. while(true) {
  1423. int tmpPageNumber = revPageCursor.getPreviousPage();
  1424. if(tmpPageNumber < 0) {
  1425. break;
  1426. }
  1427. dataPage = _addRowBufferH.setPage(getPageChannel(), tmpPageNumber);
  1428. if(dataPage.get() == PageTypes.DATA) {
  1429. // found last data page, only use if actually listed in free space
  1430. // pages
  1431. if(_freeSpacePages.containsPageNumber(tmpPageNumber)) {
  1432. pageNumber = tmpPageNumber;
  1433. }
  1434. break;
  1435. }
  1436. }
  1437. if(pageNumber == PageChannel.INVALID_PAGE_NUMBER) {
  1438. // No data pages exist (with free space). Create a new one.
  1439. return newDataPage();
  1440. }
  1441. }
  1442. if(!rowFitsOnDataPage(rowSize, dataPage, getFormat())) {
  1443. // Last data page is full. Create a new one.
  1444. writeDataPage(dataPage, pageNumber);
  1445. _freeSpacePages.removePageNumber(pageNumber);
  1446. dataPage = newDataPage();
  1447. }
  1448. return dataPage;
  1449. }
  1450. /**
  1451. * Updates the table definition after rows are modified.
  1452. */
  1453. private void updateTableDefinition(int rowCountInc) throws IOException
  1454. {
  1455. // load table definition
  1456. ByteBuffer tdefPage = _tableDefBufferH.setPage(getPageChannel(),
  1457. _tableDefPageNumber);
  1458. // make sure rowcount and autonumber are up-to-date
  1459. _rowCount += rowCountInc;
  1460. tdefPage.putInt(getFormat().OFFSET_NUM_ROWS, _rowCount);
  1461. tdefPage.putInt(getFormat().OFFSET_NEXT_AUTO_NUMBER, _lastLongAutoNumber);
  1462. int ctypeOff = getFormat().OFFSET_NEXT_COMPLEX_AUTO_NUMBER;
  1463. if(ctypeOff >= 0) {
  1464. tdefPage.putInt(ctypeOff, _lastComplexTypeAutoNumber);
  1465. }
  1466. // write any index changes
  1467. for (IndexData indexData : _indexDatas) {
  1468. // write the unique entry count for the index to the table definition
  1469. // page
  1470. tdefPage.putInt(indexData.getUniqueEntryCountOffset(),
  1471. indexData.getUniqueEntryCount());
  1472. // write the entry page for the index
  1473. indexData.update();
  1474. }
  1475. // write modified table definition
  1476. getPageChannel().writePage(tdefPage, _tableDefPageNumber);
  1477. }
  1478. /**
  1479. * Create a new data page
  1480. * @return Page number of the new page
  1481. */
  1482. private ByteBuffer newDataPage() throws IOException {
  1483. if (LOG.isDebugEnabled()) {
  1484. LOG.debug("Creating new data page");
  1485. }
  1486. ByteBuffer dataPage = _addRowBufferH.setNewPage(getPageChannel());
  1487. dataPage.put(PageTypes.DATA); //Page type
  1488. dataPage.put((byte) 1); //Unknown
  1489. dataPage.putShort((short)getFormat().DATA_PAGE_INITIAL_FREE_SPACE); //Free space in this page
  1490. dataPage.putInt(_tableDefPageNumber); //Page pointer to table definition
  1491. dataPage.putInt(0); //Unknown
  1492. dataPage.putShort((short)0); //Number of rows on this page
  1493. int pageNumber = _addRowBufferH.getPageNumber();
  1494. getPageChannel().writePage(dataPage, pageNumber);
  1495. _ownedPages.addPageNumber(pageNumber);
  1496. _freeSpacePages.addPageNumber(pageNumber);
  1497. return dataPage;
  1498. }
  1499. ByteBuffer createRow(Object[] rowArray, ByteBuffer buffer)
  1500. throws IOException
  1501. {
  1502. return createRow(rowArray, buffer, 0, Collections.<Column,byte[]>emptyMap());
  1503. }
  1504. /**
  1505. * Serialize a row of Objects into a byte buffer.
  1506. *
  1507. * @param rowArray row data, expected to be correct length for this table
  1508. * @param buffer buffer to which to write the row data
  1509. * @param minRowSize min size for result row
  1510. * @param rawVarValues optional, pre-written values for var length columns
  1511. * (enables re-use of previously written values).
  1512. * @return the given buffer, filled with the row data
  1513. */
  1514. private ByteBuffer createRow(Object[] rowArray, ByteBuffer buffer,
  1515. int minRowSize, Map<Column,byte[]> rawVarValues)
  1516. throws IOException
  1517. {
  1518. buffer.putShort(_maxColumnCount);
  1519. NullMask nullMask = new NullMask(_maxColumnCount);
  1520. //Fixed length column data comes first
  1521. int fixedDataStart = buffer.position();
  1522. int fixedDataEnd = fixedDataStart;
  1523. for (Column col : _columns) {
  1524. if(col.isVariableLength()) {
  1525. continue;
  1526. }
  1527. Object rowValue = col.getRowValue(rowArray);
  1528. if (col.getType() == DataType.BOOLEAN) {
  1529. if(Column.toBooleanValue(rowValue)) {
  1530. //Booleans are stored in the null mask
  1531. nullMask.markNotNull(col);
  1532. }
  1533. rowValue = null;
  1534. }
  1535. if(rowValue != null) {
  1536. // we have a value to write
  1537. nullMask.markNotNull(col);
  1538. // remainingRowLength is ignored when writing fixed length data
  1539. buffer.position(fixedDataStart + col.getFixedDataOffset());
  1540. buffer.put(col.write(rowValue, 0));
  1541. }
  1542. // always insert space for the entire fixed data column length
  1543. // (including null values), access expects the row to always be at least
  1544. // big enough to hold all fixed values
  1545. buffer.position(fixedDataStart + col.getFixedDataOffset() +
  1546. col.getLength());
  1547. // keep track of the end of fixed data
  1548. if(buffer.position() > fixedDataEnd) {
  1549. fixedDataEnd = buffer.position();
  1550. }
  1551. }
  1552. // reposition at end of fixed data
  1553. buffer.position(fixedDataEnd);
  1554. // only need this info if this table contains any var length data
  1555. if(_maxVarColumnCount > 0) {
  1556. int maxRowSize = getFormat().MAX_ROW_SIZE;
  1557. // figure out how much space remains for var length data. first,
  1558. // account for already written space
  1559. maxRowSize -= buffer.position();
  1560. // now, account for trailer space
  1561. int trailerSize = (nullMask.byteSize() + 4 + (_maxVarColumnCount * 2));
  1562. maxRowSize -= trailerSize;
  1563. // for each non-null long value column we need to reserve a small
  1564. // amount of space so that we don't end up running out of row space
  1565. // later by being too greedy
  1566. for (Column varCol : _varColumns) {
  1567. if((varCol.getType().isLongValue()) &&
  1568. (varCol.getRowValue(rowArray) != null)) {
  1569. maxRowSize -= getFormat().SIZE_LONG_VALUE_DEF;
  1570. }
  1571. }
  1572. //Now write out variable length column data
  1573. short[] varColumnOffsets = new short[_maxVarColumnCount];
  1574. int varColumnOffsetsIndex = 0;
  1575. for (Column varCol : _varColumns) {
  1576. short offset = (short) buffer.position();
  1577. Object rowValue = varCol.getRowValue(rowArray);
  1578. if (rowValue != null) {
  1579. // we have a value
  1580. nullMask.markNotNull(varCol);
  1581. byte[] rawValue = null;
  1582. ByteBuffer varDataBuf = null;
  1583. if(((rawValue = rawVarValues.get(varCol)) != null) &&
  1584. (rawValue.length <= maxRowSize)) {
  1585. // save time and potentially db space, re-use raw value
  1586. varDataBuf = ByteBuffer.wrap(rawValue);
  1587. } else {
  1588. // write column value
  1589. varDataBuf = varCol.write(rowValue, maxRowSize);
  1590. }
  1591. maxRowSize -= varDataBuf.remaining();
  1592. if(varCol.getType().isLongValue()) {
  1593. // we already accounted for some amount of the long value data
  1594. // above. add that space back so we don't double count
  1595. maxRowSize += getFormat().SIZE_LONG_VALUE_DEF;
  1596. }
  1597. buffer.put(varDataBuf);
  1598. }
  1599. // we do a loop here so that we fill in offsets for deleted columns
  1600. while(varColumnOffsetsIndex <= varCol.getVarLenTableIndex()) {
  1601. varColumnOffsets[varColumnOffsetsIndex++] = offset;
  1602. }
  1603. }
  1604. // fill in offsets for any remaining deleted columns
  1605. while(varColumnOffsetsIndex < varColumnOffsets.length) {
  1606. varColumnOffsets[varColumnOffsetsIndex++] = (short) buffer.position();
  1607. }
  1608. // record where we stopped writing
  1609. int eod = buffer.position();
  1610. // insert padding if necessary
  1611. padRowBuffer(buffer, minRowSize, trailerSize);
  1612. buffer.putShort((short) eod); //EOD marker
  1613. //Now write out variable length offsets
  1614. //Offsets are stored in reverse order
  1615. for (int i = _maxVarColumnCount - 1; i >= 0; i--) {
  1616. buffer.putShort(varColumnOffsets[i]);
  1617. }
  1618. buffer.putShort(_maxVarColumnCount); //Number of var length columns
  1619. } else {
  1620. // insert padding for row w/ no var cols
  1621. padRowBuffer(buffer, minRowSize, nullMask.byteSize());
  1622. }
  1623. nullMask.write(buffer); //Null mask
  1624. buffer.flip();
  1625. if (LOG.isDebugEnabled()) {
  1626. LOG.debug("Creating new data block:\n" + ByteUtil.toHexString(buffer, buffer.limit()));
  1627. }
  1628. return buffer;
  1629. }
  1630. /**
  1631. * Autonumber columns may not be modified on update.
  1632. */
  1633. private void handleAutoNumbersForUpdate(
  1634. Object[] row, ByteBuffer rowBuffer, RowState rowState)
  1635. throws IOException
  1636. {
  1637. if(_autoNumColumns.isEmpty()) {
  1638. return;
  1639. }
  1640. for(Column col : _autoNumColumns) {
  1641. col.setRowValue(row, getRowColumn(getFormat(), rowBuffer, col, rowState,
  1642. null));
  1643. }
  1644. }
  1645. /**
  1646. * Fill in all autonumber column values.
  1647. */
  1648. private void handleAutoNumbersForAdd(Object[] row)
  1649. throws IOException
  1650. {
  1651. if(_autoNumColumns.isEmpty()) {
  1652. return;
  1653. }
  1654. Object complexAutoNumber = null;
  1655. for(Column col : _autoNumColumns) {
  1656. // ignore given row value, use next autonumber
  1657. Column.AutoNumberGenerator autoNumGen = col.getAutoNumberGenerator();
  1658. Object rowValue = null;
  1659. if(autoNumGen.getType() != DataType.COMPLEX_TYPE) {
  1660. rowValue = autoNumGen.getNext(null);
  1661. } else {
  1662. // complex type auto numbers are shared across all complex columns
  1663. // in the row
  1664. complexAutoNumber = autoNumGen.getNext(complexAutoNumber);
  1665. rowValue = complexAutoNumber;
  1666. }
  1667. col.setRowValue(row, rowValue);
  1668. }
  1669. }
  1670. private static void padRowBuffer(ByteBuffer buffer, int minRowSize,
  1671. int trailerSize)
  1672. {
  1673. int pos = buffer.position();
  1674. if((pos + trailerSize) < minRowSize) {
  1675. // pad the row to get to the min byte size
  1676. int padSize = minRowSize - (pos + trailerSize);
  1677. ByteUtil.clearRange(buffer, pos, pos + padSize);
  1678. ByteUtil.forward(buffer, padSize);
  1679. }
  1680. }
  1681. /**
  1682. * @usage _general_method_
  1683. */
  1684. public int getRowCount() {
  1685. return _rowCount;
  1686. }
  1687. int getNextLongAutoNumber() {
  1688. // note, the saved value is the last one handed out, so pre-increment
  1689. return ++_lastLongAutoNumber;
  1690. }
  1691. int getLastLongAutoNumber() {
  1692. // gets the last used auto number (does not modify)
  1693. return _lastLongAutoNumber;
  1694. }
  1695. int getNextComplexTypeAutoNumber() {
  1696. // note, the saved value is the last one handed out, so pre-increment
  1697. return ++_lastComplexTypeAutoNumber;
  1698. }
  1699. int getLastComplexTypeAutoNumber() {
  1700. // gets the last used auto number (does not modify)
  1701. return _lastComplexTypeAutoNumber;
  1702. }
  1703. @Override
  1704. public String toString() {
  1705. StringBuilder rtn = new StringBuilder();
  1706. rtn.append("Type: " + _tableType +
  1707. ((_tableType == TYPE_USER) ? " (USER)" : " (SYSTEM)"));
  1708. rtn.append("\nName: " + _name);
  1709. rtn.append("\nRow count: " + _rowCount);
  1710. rtn.append("\nColumn count: " + _columns.size());
  1711. rtn.append("\nIndex (data) count: " + _indexCount);
  1712. rtn.append("\nLogical Index count: " + _logicalIndexCount);
  1713. rtn.append("\nColumns:\n");
  1714. for(Column col : _columns) {
  1715. rtn.append(col);
  1716. }
  1717. rtn.append("\nIndexes:\n");
  1718. for(Index index : _indexes) {
  1719. rtn.append(index);
  1720. }
  1721. rtn.append("\nOwned pages: " + _ownedPages + "\n");
  1722. return rtn.toString();
  1723. }
  1724. /**
  1725. * @return A simple String representation of the entire table in
  1726. * tab-delimited format
  1727. * @usage _general_method_
  1728. */
  1729. public String display() throws IOException {
  1730. return display(Long.MAX_VALUE);
  1731. }
  1732. /**
  1733. * @param limit Maximum number of rows to display
  1734. * @return A simple String representation of the entire table in
  1735. * tab-delimited format
  1736. * @usage _general_method_
  1737. */
  1738. public String display(long limit) throws IOException {
  1739. reset();
  1740. StringBuilder rtn = new StringBuilder();
  1741. for(Iterator<Column> iter = _columns.iterator(); iter.hasNext(); ) {
  1742. Column col = iter.next();
  1743. rtn.append(col.getName());
  1744. if (iter.hasNext()) {
  1745. rtn.append("\t");
  1746. }
  1747. }
  1748. rtn.append("\n");
  1749. Map<String, Object> row;
  1750. int rowCount = 0;
  1751. while ((rowCount++ < limit) && (row = getNextRow()) != null) {
  1752. for(Iterator<Object> iter = row.values().iterator(); iter.hasNext(); ) {
  1753. Object obj = iter.next();
  1754. if (obj instanceof byte[]) {
  1755. byte[] b = (byte[]) obj;
  1756. rtn.append(ByteUtil.toHexString(b));
  1757. //This block can be used to easily dump a binary column to a file
  1758. /*java.io.File f = java.io.File.createTempFile("ole", ".bin");
  1759. java.io.FileOutputStream out = new java.io.FileOutputStream(f);
  1760. out.write(b);
  1761. out.flush();
  1762. out.close();*/
  1763. } else {
  1764. rtn.append(String.valueOf(obj));
  1765. }
  1766. if (iter.hasNext()) {
  1767. rtn.append("\t");
  1768. }
  1769. }
  1770. rtn.append("\n");
  1771. }
  1772. return rtn.toString();
  1773. }
  1774. /**
  1775. * Updates free space and row info for a new row of the given size in the
  1776. * given data page. Positions the page for writing the row data.
  1777. * @return the row number of the new row
  1778. * @usage _advanced_method_
  1779. */
  1780. public static int addDataPageRow(ByteBuffer dataPage,
  1781. int rowSize,
  1782. JetFormat format,
  1783. int rowFlags)
  1784. {
  1785. int rowSpaceUsage = getRowSpaceUsage(rowSize, format);
  1786. // Decrease free space record.
  1787. short freeSpaceInPage = dataPage.getShort(format.OFFSET_FREE_SPACE);
  1788. dataPage.putShort(format.OFFSET_FREE_SPACE, (short) (freeSpaceInPage -
  1789. rowSpaceUsage));
  1790. // Increment row count record.
  1791. short rowCount = dataPage.getShort(format.OFFSET_NUM_ROWS_ON_DATA_PAGE);
  1792. dataPage.putShort(format.OFFSET_NUM_ROWS_ON_DATA_PAGE,
  1793. (short) (rowCount + 1));
  1794. // determine row position
  1795. short rowLocation = findRowEnd(dataPage, rowCount, format);
  1796. rowLocation -= rowSize;
  1797. // write row position
  1798. dataPage.putShort(getRowStartOffset(rowCount, format),
  1799. (short)(rowLocation | rowFlags));
  1800. // set position for row data
  1801. dataPage.position(rowLocation);
  1802. return rowCount;
  1803. }
  1804. /**
  1805. * Returns the row count for the current page. If the page is invalid
  1806. * ({@code null}) or the page is not a DATA page, 0 is returned.
  1807. */
  1808. private static int getRowsOnDataPage(ByteBuffer rowBuffer, JetFormat format)
  1809. throws IOException
  1810. {
  1811. int rowsOnPage = 0;
  1812. if((rowBuffer != null) && (rowBuffer.get(0) == PageTypes.DATA)) {
  1813. rowsOnPage = rowBuffer.getShort(format.OFFSET_NUM_ROWS_ON_DATA_PAGE);
  1814. }
  1815. return rowsOnPage;
  1816. }
  1817. /**
  1818. * @throws IllegalStateException if the given rowId is invalid
  1819. */
  1820. private static void requireValidRowId(RowId rowId) {
  1821. if(!rowId.isValid()) {
  1822. throw new IllegalArgumentException("Given rowId is invalid: " + rowId);
  1823. }
  1824. }
  1825. /**
  1826. * @throws IllegalStateException if the given row is invalid or deleted
  1827. */
  1828. private static void requireNonDeletedRow(RowState rowState, RowId rowId) {
  1829. if(!rowState.isValid()) {
  1830. throw new IllegalArgumentException(
  1831. "Given rowId is invalid for this table: " + rowId);
  1832. }
  1833. if(rowState.isDeleted()) {
  1834. throw new IllegalStateException("Row is deleted: " + rowId);
  1835. }
  1836. }
  1837. /**
  1838. * @usage _advanced_method_
  1839. */
  1840. public static boolean isDeletedRow(short rowStart) {
  1841. return ((rowStart & DELETED_ROW_MASK) != 0);
  1842. }
  1843. /**
  1844. * @usage _advanced_method_
  1845. */
  1846. public static boolean isOverflowRow(short rowStart) {
  1847. return ((rowStart & OVERFLOW_ROW_MASK) != 0);
  1848. }
  1849. /**
  1850. * @usage _advanced_method_
  1851. */
  1852. public static short cleanRowStart(short rowStart) {
  1853. return (short)(rowStart & OFFSET_MASK);
  1854. }
  1855. /**
  1856. * @usage _advanced_method_
  1857. */
  1858. public static short findRowStart(ByteBuffer buffer, int rowNum,
  1859. JetFormat format)
  1860. {
  1861. return cleanRowStart(
  1862. buffer.getShort(getRowStartOffset(rowNum, format)));
  1863. }
  1864. /**
  1865. * @usage _advanced_method_
  1866. */
  1867. public static int getRowStartOffset(int rowNum, JetFormat format)
  1868. {
  1869. return format.OFFSET_ROW_START + (format.SIZE_ROW_LOCATION * rowNum);
  1870. }
  1871. /**
  1872. * @usage _advanced_method_
  1873. */
  1874. public static short findRowEnd(ByteBuffer buffer, int rowNum,
  1875. JetFormat format)
  1876. {
  1877. return (short)((rowNum == 0) ?
  1878. format.PAGE_SIZE :
  1879. cleanRowStart(
  1880. buffer.getShort(getRowEndOffset(rowNum, format))));
  1881. }
  1882. /**
  1883. * @usage _advanced_method_
  1884. */
  1885. public static int getRowEndOffset(int rowNum, JetFormat format)
  1886. {
  1887. return format.OFFSET_ROW_START + (format.SIZE_ROW_LOCATION * (rowNum - 1));
  1888. }
  1889. /**
  1890. * @usage _advanced_method_
  1891. */
  1892. public static int getRowSpaceUsage(int rowSize, JetFormat format)
  1893. {
  1894. return rowSize + format.SIZE_ROW_LOCATION;
  1895. }
  1896. /**
  1897. * @return the "AutoNumber" columns in the given collection of columns.
  1898. * @usage _advanced_method_
  1899. */
  1900. public static List<Column> getAutoNumberColumns(Collection<Column> columns) {
  1901. List<Column> autoCols = new ArrayList<Column>(1);
  1902. for(Column c : columns) {
  1903. if(c.isAutoNumber()) {
  1904. autoCols.add(c);
  1905. }
  1906. }
  1907. return autoCols;
  1908. }
  1909. /**
  1910. * Returns {@code true} if a row of the given size will fit on the given
  1911. * data page, {@code false} otherwise.
  1912. * @usage _advanced_method_
  1913. */
  1914. public static boolean rowFitsOnDataPage(
  1915. int rowLength, ByteBuffer dataPage, JetFormat format)
  1916. throws IOException
  1917. {
  1918. int rowSpaceUsage = getRowSpaceUsage(rowLength, format);
  1919. short freeSpaceInPage = dataPage.getShort(format.OFFSET_FREE_SPACE);
  1920. int rowsOnPage = getRowsOnDataPage(dataPage, format);
  1921. return ((rowSpaceUsage <= freeSpaceInPage) &&
  1922. (rowsOnPage < format.MAX_NUM_ROWS_ON_DATA_PAGE));
  1923. }
  1924. /**
  1925. * Duplicates and returns a row of data, optionally with a longer length
  1926. * filled with {@code null}.
  1927. */
  1928. static Object[] dupeRow(Object[] row, int newRowLength) {
  1929. Object[] copy = new Object[newRowLength];
  1930. System.arraycopy(row, 0, copy, 0, row.length);
  1931. return copy;
  1932. }
  1933. /** various statuses for the row data */
  1934. private enum RowStatus {
  1935. INIT, INVALID_PAGE, INVALID_ROW, VALID, DELETED, NORMAL, OVERFLOW;
  1936. }
  1937. /** the phases the RowState moves through as the data is parsed */
  1938. private enum RowStateStatus {
  1939. INIT, AT_HEADER, AT_FINAL;
  1940. }
  1941. /**
  1942. * Maintains the state of reading a row of data.
  1943. * @usage _advanced_class_
  1944. */
  1945. public final class RowState
  1946. {
  1947. /** Buffer used for reading the header row data pages */
  1948. private final TempPageHolder _headerRowBufferH;
  1949. /** the header rowId */
  1950. private RowId _headerRowId = RowId.FIRST_ROW_ID;
  1951. /** the number of rows on the header page */
  1952. private int _rowsOnHeaderPage;
  1953. /** the rowState status */
  1954. private RowStateStatus _status = RowStateStatus.INIT;
  1955. /** the row status */
  1956. private RowStatus _rowStatus = RowStatus.INIT;
  1957. /** buffer used for reading overflow pages */
  1958. private final TempPageHolder _overflowRowBufferH =
  1959. TempPageHolder.newHolder(TempBufferHolder.Type.SOFT);
  1960. /** the row buffer which contains the final data (after following any
  1961. overflow pointers) */
  1962. private ByteBuffer _finalRowBuffer;
  1963. /** the rowId which contains the final data (after following any overflow
  1964. pointers) */
  1965. private RowId _finalRowId = null;
  1966. /** true if the row values array has data */
  1967. private boolean _haveRowValues;
  1968. /** values read from the last row */
  1969. private final Object[] _rowValues;
  1970. /** null mask for the last row */
  1971. private NullMask _nullMask;
  1972. /** last modification count seen on the table we track this so that the
  1973. rowState can detect updates to the table and re-read any buffered
  1974. data */
  1975. private int _lastModCount;
  1976. /** optional error handler to use when row errors are encountered */
  1977. private ErrorHandler _errorHandler;
  1978. /** cached variable column offsets for jump-table based rows */
  1979. private short[] _varColOffsets;
  1980. private RowState(TempBufferHolder.Type headerType) {
  1981. _headerRowBufferH = TempPageHolder.newHolder(headerType);
  1982. _rowValues = new Object[Table.this.getColumnCount()];
  1983. _lastModCount = Table.this._modCount;
  1984. }
  1985. public Table getTable() {
  1986. return Table.this;
  1987. }
  1988. public ErrorHandler getErrorHandler() {
  1989. return((_errorHandler != null) ? _errorHandler :
  1990. getTable().getErrorHandler());
  1991. }
  1992. public void setErrorHandler(ErrorHandler newErrorHandler) {
  1993. _errorHandler = newErrorHandler;
  1994. }
  1995. public void reset() {
  1996. _finalRowId = null;
  1997. _finalRowBuffer = null;
  1998. _rowsOnHeaderPage = 0;
  1999. _status = RowStateStatus.INIT;
  2000. _rowStatus = RowStatus.INIT;
  2001. _varColOffsets = null;
  2002. _nullMask = null;
  2003. if(_haveRowValues) {
  2004. Arrays.fill(_rowValues, null);
  2005. _haveRowValues = false;
  2006. }
  2007. }
  2008. public boolean isUpToDate() {
  2009. return(Table.this._modCount == _lastModCount);
  2010. }
  2011. private void checkForModification() {
  2012. if(!isUpToDate()) {
  2013. reset();
  2014. _headerRowBufferH.invalidate();
  2015. _overflowRowBufferH.invalidate();
  2016. _lastModCount = Table.this._modCount;
  2017. }
  2018. }
  2019. private ByteBuffer getFinalPage()
  2020. throws IOException
  2021. {
  2022. if(_finalRowBuffer == null) {
  2023. // (re)load current page
  2024. _finalRowBuffer = getHeaderPage();
  2025. }
  2026. return _finalRowBuffer;
  2027. }
  2028. public RowId getFinalRowId() {
  2029. if(_finalRowId == null) {
  2030. _finalRowId = getHeaderRowId();
  2031. }
  2032. return _finalRowId;
  2033. }
  2034. private void setRowStatus(RowStatus rowStatus) {
  2035. _rowStatus = rowStatus;
  2036. }
  2037. public boolean isValid() {
  2038. return(_rowStatus.ordinal() >= RowStatus.VALID.ordinal());
  2039. }
  2040. public boolean isDeleted() {
  2041. return(_rowStatus == RowStatus.DELETED);
  2042. }
  2043. public boolean isOverflow() {
  2044. return(_rowStatus == RowStatus.OVERFLOW);
  2045. }
  2046. public boolean isHeaderPageNumberValid() {
  2047. return(_rowStatus.ordinal() > RowStatus.INVALID_PAGE.ordinal());
  2048. }
  2049. public boolean isHeaderRowNumberValid() {
  2050. return(_rowStatus.ordinal() > RowStatus.INVALID_ROW.ordinal());
  2051. }
  2052. private void setStatus(RowStateStatus status) {
  2053. _status = status;
  2054. }
  2055. public boolean isAtHeaderRow() {
  2056. return(_status.ordinal() >= RowStateStatus.AT_HEADER.ordinal());
  2057. }
  2058. public boolean isAtFinalRow() {
  2059. return(_status.ordinal() >= RowStateStatus.AT_FINAL.ordinal());
  2060. }
  2061. private Object setRowValue(int idx, Object value) {
  2062. _haveRowValues = true;
  2063. _rowValues[idx] = value;
  2064. return value;
  2065. }
  2066. public Object[] getRowValues() {
  2067. return dupeRow(_rowValues, _rowValues.length);
  2068. }
  2069. public NullMask getNullMask(ByteBuffer rowBuffer) throws IOException {
  2070. if(_nullMask == null) {
  2071. _nullMask = getRowNullMask(rowBuffer);
  2072. }
  2073. return _nullMask;
  2074. }
  2075. private short[] getVarColOffsets() {
  2076. return _varColOffsets;
  2077. }
  2078. private void setVarColOffsets(short[] varColOffsets) {
  2079. _varColOffsets = varColOffsets;
  2080. }
  2081. public RowId getHeaderRowId() {
  2082. return _headerRowId;
  2083. }
  2084. public int getRowsOnHeaderPage() {
  2085. return _rowsOnHeaderPage;
  2086. }
  2087. private ByteBuffer getHeaderPage()
  2088. throws IOException
  2089. {
  2090. checkForModification();
  2091. return _headerRowBufferH.getPage(getPageChannel());
  2092. }
  2093. private ByteBuffer setHeaderRow(RowId rowId)
  2094. throws IOException
  2095. {
  2096. checkForModification();
  2097. // don't do any work if we are already positioned correctly
  2098. if(isAtHeaderRow() && (getHeaderRowId().equals(rowId))) {
  2099. return(isValid() ? getHeaderPage() : null);
  2100. }
  2101. // rejigger everything
  2102. reset();
  2103. _headerRowId = rowId;
  2104. _finalRowId = rowId;
  2105. int pageNumber = rowId.getPageNumber();
  2106. int rowNumber = rowId.getRowNumber();
  2107. if((pageNumber < 0) || !_ownedPages.containsPageNumber(pageNumber)) {
  2108. setRowStatus(RowStatus.INVALID_PAGE);
  2109. return null;
  2110. }
  2111. _finalRowBuffer = _headerRowBufferH.setPage(getPageChannel(),
  2112. pageNumber);
  2113. _rowsOnHeaderPage = getRowsOnDataPage(_finalRowBuffer, getFormat());
  2114. if((rowNumber < 0) || (rowNumber >= _rowsOnHeaderPage)) {
  2115. setRowStatus(RowStatus.INVALID_ROW);
  2116. return null;
  2117. }
  2118. setRowStatus(RowStatus.VALID);
  2119. return _finalRowBuffer;
  2120. }
  2121. private ByteBuffer setOverflowRow(RowId rowId)
  2122. throws IOException
  2123. {
  2124. // this should never see modifications because it only happens within
  2125. // the positionAtRowData method
  2126. if(!isUpToDate()) {
  2127. throw new IllegalStateException("Table modified while searching?");
  2128. }
  2129. if(_rowStatus != RowStatus.OVERFLOW) {
  2130. throw new IllegalStateException("Row is not an overflow row?");
  2131. }
  2132. _finalRowId = rowId;
  2133. _finalRowBuffer = _overflowRowBufferH.setPage(getPageChannel(),
  2134. rowId.getPageNumber());
  2135. return _finalRowBuffer;
  2136. }
  2137. private Object handleRowError(Column column,
  2138. byte[] columnData,
  2139. Exception error)
  2140. throws IOException
  2141. {
  2142. return getErrorHandler().handleRowError(column, columnData,
  2143. this, error);
  2144. }
  2145. @Override
  2146. public String toString()
  2147. {
  2148. return "RowState: headerRowId = " + _headerRowId + ", finalRowId = " +
  2149. _finalRowId;
  2150. }
  2151. }
  2152. }