Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

TableImpl.java 110KB

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