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.

TableImpl.java 91KB

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