選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

TableImpl.java 111KB

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