Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

TableImpl.java 115KB

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