Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

TableImpl.java 110KB

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