You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

DatabaseImpl.java 90KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774
  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.File;
  15. import java.io.FileNotFoundException;
  16. import java.io.IOException;
  17. import java.io.InputStream;
  18. import java.lang.ref.ReferenceQueue;
  19. import java.lang.ref.WeakReference;
  20. import java.nio.ByteBuffer;
  21. import java.nio.channels.Channels;
  22. import java.nio.channels.FileChannel;
  23. import java.nio.channels.ReadableByteChannel;
  24. import java.nio.charset.Charset;
  25. import java.nio.file.Files;
  26. import java.nio.file.OpenOption;
  27. import java.nio.file.Path;
  28. import java.nio.file.StandardOpenOption;
  29. import java.text.SimpleDateFormat;
  30. import java.time.ZoneId;
  31. import java.util.ArrayList;
  32. import java.util.Arrays;
  33. import java.util.Collection;
  34. import java.util.Collections;
  35. import java.util.Date;
  36. import java.util.EnumMap;
  37. import java.util.HashMap;
  38. import java.util.HashSet;
  39. import java.util.Iterator;
  40. import java.util.List;
  41. import java.util.Map;
  42. import java.util.NoSuchElementException;
  43. import java.util.Set;
  44. import java.util.TimeZone;
  45. import java.util.TreeSet;
  46. import java.util.regex.Pattern;
  47. import com.healthmarketscience.jackcess.ColumnBuilder;
  48. import com.healthmarketscience.jackcess.Cursor;
  49. import com.healthmarketscience.jackcess.CursorBuilder;
  50. import com.healthmarketscience.jackcess.DataType;
  51. import com.healthmarketscience.jackcess.Database;
  52. import com.healthmarketscience.jackcess.DatabaseBuilder;
  53. import com.healthmarketscience.jackcess.DateTimeType;
  54. import com.healthmarketscience.jackcess.Index;
  55. import com.healthmarketscience.jackcess.IndexBuilder;
  56. import com.healthmarketscience.jackcess.IndexCursor;
  57. import com.healthmarketscience.jackcess.PropertyMap;
  58. import com.healthmarketscience.jackcess.Relationship;
  59. import com.healthmarketscience.jackcess.Row;
  60. import com.healthmarketscience.jackcess.RuntimeIOException;
  61. import com.healthmarketscience.jackcess.Table;
  62. import com.healthmarketscience.jackcess.TableBuilder;
  63. import com.healthmarketscience.jackcess.TableMetaData;
  64. import com.healthmarketscience.jackcess.expr.EvalConfig;
  65. import com.healthmarketscience.jackcess.impl.query.QueryImpl;
  66. import com.healthmarketscience.jackcess.query.Query;
  67. import com.healthmarketscience.jackcess.util.CaseInsensitiveColumnMatcher;
  68. import com.healthmarketscience.jackcess.util.ColumnValidatorFactory;
  69. import com.healthmarketscience.jackcess.util.ErrorHandler;
  70. import com.healthmarketscience.jackcess.util.LinkResolver;
  71. import com.healthmarketscience.jackcess.util.ReadOnlyFileChannel;
  72. import com.healthmarketscience.jackcess.util.SimpleColumnValidatorFactory;
  73. import com.healthmarketscience.jackcess.util.TableIterableBuilder;
  74. import org.apache.commons.lang3.StringUtils;
  75. import org.apache.commons.lang3.builder.ToStringBuilder;
  76. import org.apache.commons.logging.Log;
  77. import org.apache.commons.logging.LogFactory;
  78. /**
  79. *
  80. * @author Tim McCune
  81. * @usage _intermediate_class_
  82. */
  83. public class DatabaseImpl implements Database, DateTimeContext
  84. {
  85. private static final Log LOG = LogFactory.getLog(DatabaseImpl.class);
  86. /** this is the default "userId" used if we cannot find existing info. this
  87. seems to be some standard "Admin" userId for access files */
  88. private static final byte[] SYS_DEFAULT_SID = new byte[] {
  89. (byte) 0xA6, (byte) 0x33};
  90. /** the default value for the resource path used to load classpath
  91. * resources.
  92. */
  93. public static final String DEFAULT_RESOURCE_PATH =
  94. "com/healthmarketscience/jackcess/";
  95. /** the resource path to be used when loading classpath resources */
  96. static final String RESOURCE_PATH =
  97. System.getProperty(RESOURCE_PATH_PROPERTY, DEFAULT_RESOURCE_PATH);
  98. /** whether or not this jvm has "broken" nio support */
  99. static final boolean BROKEN_NIO = Boolean.TRUE.toString().equalsIgnoreCase(
  100. System.getProperty(BROKEN_NIO_PROPERTY));
  101. /** additional internal details about each FileFormat */
  102. private static final Map<Database.FileFormat,FileFormatDetails> FILE_FORMAT_DETAILS =
  103. new EnumMap<Database.FileFormat,FileFormatDetails>(Database.FileFormat.class);
  104. static {
  105. addFileFormatDetails(FileFormat.V1997, null, JetFormat.VERSION_3);
  106. addFileFormatDetails(FileFormat.GENERIC_JET4, null, JetFormat.VERSION_4);
  107. addFileFormatDetails(FileFormat.V2000, "empty", JetFormat.VERSION_4);
  108. addFileFormatDetails(FileFormat.V2003, "empty2003", JetFormat.VERSION_4);
  109. addFileFormatDetails(FileFormat.V2007, "empty2007", JetFormat.VERSION_12);
  110. addFileFormatDetails(FileFormat.V2010, "empty2010", JetFormat.VERSION_14);
  111. addFileFormatDetails(FileFormat.V2016, "empty2016", JetFormat.VERSION_16);
  112. addFileFormatDetails(FileFormat.V2019, "empty2019", JetFormat.VERSION_17);
  113. addFileFormatDetails(FileFormat.MSISAM, null, JetFormat.VERSION_MSISAM);
  114. }
  115. /** System catalog always lives on page 2 */
  116. private static final int PAGE_SYSTEM_CATALOG = 2;
  117. /** Name of the system catalog */
  118. private static final String TABLE_SYSTEM_CATALOG = "MSysObjects";
  119. /** this is the access control bit field for created tables. the value used
  120. is equivalent to full access (Visual Basic DAO PermissionEnum constant:
  121. dbSecFullAccess) */
  122. private static final Integer SYS_FULL_ACCESS_ACM = 1048575;
  123. /** ACE table column name of the actual access control entry */
  124. private static final String ACE_COL_ACM = "ACM";
  125. /** ACE table column name of the inheritable attributes flag */
  126. private static final String ACE_COL_F_INHERITABLE = "FInheritable";
  127. /** ACE table column name of the relevant objectId */
  128. private static final String ACE_COL_OBJECT_ID = "ObjectId";
  129. /** ACE table column name of the relevant userId */
  130. private static final String ACE_COL_SID = "SID";
  131. /** Relationship table column name of the column count */
  132. private static final String REL_COL_COLUMN_COUNT = "ccolumn";
  133. /** Relationship table column name of the flags */
  134. private static final String REL_COL_FLAGS = "grbit";
  135. /** Relationship table column name of the index of the columns */
  136. private static final String REL_COL_COLUMN_INDEX = "icolumn";
  137. /** Relationship table column name of the "to" column name */
  138. private static final String REL_COL_TO_COLUMN = "szColumn";
  139. /** Relationship table column name of the "to" table name */
  140. private static final String REL_COL_TO_TABLE = "szObject";
  141. /** Relationship table column name of the "from" column name */
  142. private static final String REL_COL_FROM_COLUMN = "szReferencedColumn";
  143. /** Relationship table column name of the "from" table name */
  144. private static final String REL_COL_FROM_TABLE = "szReferencedObject";
  145. /** Relationship table column name of the relationship */
  146. private static final String REL_COL_NAME = "szRelationship";
  147. /** System catalog column name of the page on which system object definitions
  148. are stored */
  149. private static final String CAT_COL_ID = "Id";
  150. /** System catalog column name of the name of a system object */
  151. private static final String CAT_COL_NAME = "Name";
  152. private static final String CAT_COL_OWNER = "Owner";
  153. /** System catalog column name of a system object's parent's id */
  154. private static final String CAT_COL_PARENT_ID = "ParentId";
  155. /** System catalog column name of the type of a system object */
  156. private static final String CAT_COL_TYPE = "Type";
  157. /** System catalog column name of the date a system object was created */
  158. private static final String CAT_COL_DATE_CREATE = "DateCreate";
  159. /** System catalog column name of the date a system object was updated */
  160. private static final String CAT_COL_DATE_UPDATE = "DateUpdate";
  161. /** System catalog column name of the flags column */
  162. private static final String CAT_COL_FLAGS = "Flags";
  163. /** System catalog column name of the properties column */
  164. static final String CAT_COL_PROPS = "LvProp";
  165. /** System catalog column name of the remote database */
  166. private static final String CAT_COL_DATABASE = "Database";
  167. /** System catalog column name of the remote table name */
  168. private static final String CAT_COL_FOREIGN_NAME = "ForeignName";
  169. /** top-level parentid for a database */
  170. private static final int DB_PARENT_ID = 0xF000000;
  171. /** the maximum size of any of the included "empty db" resources */
  172. private static final long MAX_EMPTYDB_SIZE = 440000L;
  173. /** this object is a "system" object */
  174. static final int SYSTEM_OBJECT_FLAG = 0x80000000;
  175. /** this object is another type of "system" object */
  176. static final int ALT_SYSTEM_OBJECT_FLAG = 0x02;
  177. /** this object is hidden */
  178. public static final int HIDDEN_OBJECT_FLAG = 0x08;
  179. /** all flags which seem to indicate some type of system object */
  180. static final int SYSTEM_OBJECT_FLAGS =
  181. SYSTEM_OBJECT_FLAG | ALT_SYSTEM_OBJECT_FLAG;
  182. /** read-only channel access mode */
  183. public static final OpenOption[] RO_CHANNEL_OPTS =
  184. {StandardOpenOption.READ};
  185. /** read/write channel access mode for existing files */
  186. public static final OpenOption[] RW_CHANNEL_OPTS =
  187. {StandardOpenOption.READ, StandardOpenOption.WRITE};
  188. /** read/write/create channel access mode for new files */
  189. public static final OpenOption[] RWC_CHANNEL_OPTS =
  190. {StandardOpenOption.READ, StandardOpenOption.WRITE,
  191. StandardOpenOption.CREATE};
  192. /** Name of the system object that is the parent of all tables */
  193. private static final String SYSTEM_OBJECT_NAME_TABLES = "Tables";
  194. /** Name of the system object that is the parent of all databases */
  195. private static final String SYSTEM_OBJECT_NAME_DATABASES = "Databases";
  196. /** Name of the system object that is the parent of all relationships */
  197. private static final String SYSTEM_OBJECT_NAME_RELATIONSHIPS = "Relationships";
  198. /** Name of the table that contains system access control entries */
  199. private static final String TABLE_SYSTEM_ACES = "MSysACEs";
  200. /** Name of the table that contains table relationships */
  201. private static final String TABLE_SYSTEM_RELATIONSHIPS = "MSysRelationships";
  202. /** Name of the table that contains queries */
  203. private static final String TABLE_SYSTEM_QUERIES = "MSysQueries";
  204. /** Name of the table that contains complex type information */
  205. private static final String TABLE_SYSTEM_COMPLEX_COLS = "MSysComplexColumns";
  206. /** Name of the main database properties object */
  207. private static final String OBJECT_NAME_DB_PROPS = "MSysDb";
  208. /** Name of the summary properties object */
  209. private static final String OBJECT_NAME_SUMMARY_PROPS = "SummaryInfo";
  210. /** Name of the user-defined properties object */
  211. private static final String OBJECT_NAME_USERDEF_PROPS = "UserDefined";
  212. /** System object type for table definitions */
  213. static final Short TYPE_TABLE = 1;
  214. /** System object type for query definitions */
  215. private static final Short TYPE_QUERY = 5;
  216. /** System object type for linked table definitions */
  217. private static final Short TYPE_LINKED_TABLE = 6;
  218. /** System object type for relationships */
  219. private static final Short TYPE_RELATIONSHIP = 8;
  220. /** max number of table lookups to cache */
  221. private static final int MAX_CACHED_LOOKUP_TABLES = 50;
  222. /** the columns to read when reading system catalog normally */
  223. private static Collection<String> SYSTEM_CATALOG_COLUMNS =
  224. new HashSet<String>(Arrays.asList(CAT_COL_NAME, CAT_COL_TYPE, CAT_COL_ID,
  225. CAT_COL_FLAGS, CAT_COL_PARENT_ID));
  226. /** the columns to read when finding table details */
  227. private static Collection<String> SYSTEM_CATALOG_TABLE_DETAIL_COLUMNS =
  228. new HashSet<String>(Arrays.asList(CAT_COL_NAME, CAT_COL_TYPE, CAT_COL_ID,
  229. CAT_COL_FLAGS, CAT_COL_PARENT_ID,
  230. CAT_COL_DATABASE, CAT_COL_FOREIGN_NAME));
  231. /** the columns to read when getting object propertyes */
  232. private static Collection<String> SYSTEM_CATALOG_PROPS_COLUMNS =
  233. new HashSet<String>(Arrays.asList(CAT_COL_ID, CAT_COL_PROPS));
  234. /** regex matching characters which are invalid in identifier names */
  235. private static final Pattern INVALID_IDENTIFIER_CHARS =
  236. Pattern.compile("[\\p{Cntrl}.!`\\]\\[]");
  237. /** the File of the database */
  238. private final Path _file;
  239. /** the simple name of the database */
  240. private final String _name;
  241. /** whether or not this db is read-only */
  242. private final boolean _readOnly;
  243. /** Buffer to hold database pages */
  244. private ByteBuffer _buffer;
  245. /** ID of the Tables system object */
  246. private Integer _tableParentId;
  247. /** Format that the containing database is in */
  248. private final JetFormat _format;
  249. /**
  250. * Cache map of UPPERCASE table names to page numbers containing their
  251. * definition and their stored table name (max size
  252. * MAX_CACHED_LOOKUP_TABLES).
  253. */
  254. private final Map<String, TableInfo> _tableLookup =
  255. new SimpleCache<String,TableInfo>(MAX_CACHED_LOOKUP_TABLES);
  256. /** set of table names as stored in the mdb file, created on demand */
  257. private Set<String> _tableNames;
  258. /** Reads and writes database pages */
  259. private final PageChannel _pageChannel;
  260. /** System catalog table */
  261. private TableImpl _systemCatalog;
  262. /** utility table finder */
  263. private TableFinder _tableFinder;
  264. /** System access control entries table (initialized on first use) */
  265. private TableImpl _accessControlEntries;
  266. /** ID of the Relationships system object */
  267. private Integer _relParentId;
  268. /** SIDs to use for the ACEs added for new relationships */
  269. private final List<byte[]> _newRelSIDs = new ArrayList<byte[]>();
  270. /** System relationships table (initialized on first use) */
  271. private TableImpl _relationships;
  272. /** System queries table (initialized on first use) */
  273. private TableImpl _queries;
  274. /** System complex columns table (initialized on first use) */
  275. private TableImpl _complexCols;
  276. /** SIDs to use for the ACEs added for new tables */
  277. private final List<byte[]> _newTableSIDs = new ArrayList<byte[]>();
  278. /** optional error handler to use when row errors are encountered */
  279. private ErrorHandler _dbErrorHandler;
  280. /** the file format of the database */
  281. private FileFormat _fileFormat;
  282. /** charset to use when handling text */
  283. private Charset _charset;
  284. /** timezone to use when handling dates */
  285. private TimeZone _timeZone;
  286. /** zoneId to use when handling dates */
  287. private ZoneId _zoneId;
  288. /** language sort order to be used for textual columns */
  289. private ColumnImpl.SortOrder _defaultSortOrder;
  290. /** default code page to be used for textual columns (in some dbs) */
  291. private Short _defaultCodePage;
  292. /** the ordering used for table columns */
  293. private Table.ColumnOrder _columnOrder;
  294. /** whether or not enforcement of foreign-keys is enabled */
  295. private boolean _enforceForeignKeys;
  296. /** whether or not auto numbers can be directly inserted by the user */
  297. private boolean _allowAutoNumInsert;
  298. /** whether or not to evaluate expressions */
  299. private boolean _evaluateExpressions;
  300. /** factory for ColumnValidators */
  301. private ColumnValidatorFactory _validatorFactory = SimpleColumnValidatorFactory.INSTANCE;
  302. /** cache of in-use tables */
  303. private final TableCache _tableCache = new TableCache();
  304. /** handler for reading/writing properteies */
  305. private PropertyMaps.Handler _propsHandler;
  306. /** ID of the Databases system object */
  307. private Integer _dbParentId;
  308. /** owner of objects we create */
  309. private byte[] _newObjOwner;
  310. /** core database properties */
  311. private PropertyMaps _dbPropMaps;
  312. /** summary properties */
  313. private PropertyMaps _summaryPropMaps;
  314. /** user-defined properties */
  315. private PropertyMaps _userDefPropMaps;
  316. /** linked table resolver */
  317. private LinkResolver _linkResolver;
  318. /** any linked databases which have been opened */
  319. private Map<String,Database> _linkedDbs;
  320. /** shared state used when enforcing foreign keys */
  321. private final FKEnforcer.SharedState _fkEnforcerSharedState =
  322. FKEnforcer.initSharedState();
  323. /** shared context for evaluating expressions */
  324. private DBEvalContext _evalCtx;
  325. /** factory for the appropriate date/time type */
  326. private ColumnImpl.DateTimeFactory _dtf;
  327. /**
  328. * Open an existing Database. If the existing file is not writeable or the
  329. * readOnly flag is {@code true}, the file will be opened read-only.
  330. * @param mdbFile File containing the database
  331. * @param readOnly iff {@code true}, force opening file in read-only
  332. * mode
  333. * @param channel pre-opened FileChannel. if provided explicitly, it will
  334. * not be closed by this Database instance
  335. * @param autoSync whether or not to enable auto-syncing on write. if
  336. * {@code true}, writes will be immediately flushed to disk.
  337. * This leaves the database in a (fairly) consistent state
  338. * on each write, but can be very inefficient for many
  339. * updates. if {@code false}, flushing to disk happens at
  340. * the jvm's leisure, which can be much faster, but may
  341. * leave the database in an inconsistent state if failures
  342. * are encountered during writing. Writes may be flushed at
  343. * any time using {@link #flush}.
  344. * @param charset Charset to use, if {@code null}, uses default
  345. * @param timeZone TimeZone to use, if {@code null}, uses default
  346. * @param provider CodecProvider for handling page encoding/decoding, may be
  347. * {@code null} if no special encoding is necessary
  348. * @usage _advanced_method_
  349. */
  350. public static DatabaseImpl open(
  351. Path mdbFile, boolean readOnly, FileChannel channel,
  352. boolean autoSync, Charset charset, TimeZone timeZone,
  353. CodecProvider provider)
  354. throws IOException
  355. {
  356. boolean closeChannel = false;
  357. if(channel == null) {
  358. if(!Files.isReadable(mdbFile)) {
  359. throw new FileNotFoundException("given file does not exist: " +
  360. mdbFile);
  361. }
  362. // force read-only for non-writable files
  363. readOnly |= !Files.isWritable(mdbFile);
  364. // open file channel
  365. channel = openChannel(mdbFile, readOnly, false);
  366. closeChannel = true;
  367. }
  368. boolean success = false;
  369. try {
  370. boolean wrapChannelRO = false;
  371. if(!readOnly) {
  372. // verify that format supports writing
  373. JetFormat jetFormat = JetFormat.getFormat(channel);
  374. if(jetFormat.READ_ONLY) {
  375. // force read-only mode
  376. wrapChannelRO = true;
  377. readOnly = true;
  378. }
  379. } else if(!closeChannel) {
  380. // we are in read-only mode but the channel was opened externally, so
  381. // we don't know if it is enforcing read-only status. wrap it just to
  382. // be safe
  383. wrapChannelRO = true;
  384. }
  385. if(wrapChannelRO) {
  386. // wrap the channel with a read-only version to enforce
  387. // non-writability
  388. channel = new ReadOnlyFileChannel(channel);
  389. }
  390. DatabaseImpl db = new DatabaseImpl(mdbFile, channel, closeChannel, autoSync,
  391. null, charset, timeZone, provider,
  392. readOnly);
  393. success = true;
  394. return db;
  395. } finally {
  396. if(!success && closeChannel) {
  397. // something blew up, shutdown the channel (quietly)
  398. ByteUtil.closeQuietly(channel);
  399. }
  400. }
  401. }
  402. /**
  403. * Create a new Database for the given fileFormat
  404. * @param fileFormat version of new database.
  405. * @param mdbFile Location to write the new database to. <b>If this file
  406. * already exists, it will be overwritten.</b>
  407. * @param channel pre-opened FileChannel. if provided explicitly, it will
  408. * not be closed by this Database instance
  409. * @param autoSync whether or not to enable auto-syncing on write. if
  410. * {@code true}, writes will be immediately flushed to disk.
  411. * This leaves the database in a (fairly) consistent state
  412. * on each write, but can be very inefficient for many
  413. * updates. if {@code false}, flushing to disk happens at
  414. * the jvm's leisure, which can be much faster, but may
  415. * leave the database in an inconsistent state if failures
  416. * are encountered during writing. Writes may be flushed at
  417. * any time using {@link #flush}.
  418. * @param charset Charset to use, if {@code null}, uses default
  419. * @param timeZone TimeZone to use, if {@code null}, uses default
  420. * @usage _advanced_method_
  421. */
  422. public static DatabaseImpl create(FileFormat fileFormat, Path mdbFile,
  423. FileChannel channel, boolean autoSync,
  424. Charset charset, TimeZone timeZone)
  425. throws IOException
  426. {
  427. FileFormatDetails details = getFileFormatDetails(fileFormat);
  428. if (details.getFormat().READ_ONLY) {
  429. throw new IOException("File format " + fileFormat +
  430. " does not support writing for " + mdbFile);
  431. }
  432. if(details.getEmptyFilePath() == null) {
  433. throw new IOException("File format " + fileFormat +
  434. " does not support file creation for " + mdbFile);
  435. }
  436. boolean closeChannel = false;
  437. if(channel == null) {
  438. channel = openChannel(mdbFile, false, true);
  439. closeChannel = true;
  440. }
  441. boolean success = false;
  442. try {
  443. channel.truncate(0);
  444. transferDbFrom(channel, getResourceAsStream(details.getEmptyFilePath()));
  445. channel.force(true);
  446. DatabaseImpl db = new DatabaseImpl(mdbFile, channel, closeChannel, autoSync,
  447. fileFormat, charset, timeZone, null,
  448. false);
  449. success = true;
  450. return db;
  451. } finally {
  452. if(!success && closeChannel) {
  453. // something blew up, shutdown the channel (quietly)
  454. ByteUtil.closeQuietly(channel);
  455. }
  456. }
  457. }
  458. /**
  459. * Package visible only to support unit tests via DatabaseTest.openChannel().
  460. * @param mdbFile file to open
  461. * @param readOnly true if read-only
  462. * @return a FileChannel on the given file.
  463. * @exception FileNotFoundException
  464. * if the mode is <tt>"r"</tt> but the given file object does
  465. * not denote an existing regular file, or if the mode begins
  466. * with <tt>"rw"</tt> but the given file object does not denote
  467. * an existing, writable regular file and a new regular file of
  468. * that name cannot be created, or if some other error occurs
  469. * while opening or creating the file
  470. */
  471. static FileChannel openChannel(
  472. Path mdbFile, boolean readOnly, boolean create)
  473. throws IOException
  474. {
  475. OpenOption[] opts = (readOnly ? RO_CHANNEL_OPTS :
  476. (create ? RWC_CHANNEL_OPTS : RW_CHANNEL_OPTS));
  477. return FileChannel.open(mdbFile, opts);
  478. }
  479. /**
  480. * Create a new database by reading it in from a FileChannel.
  481. * @param file the File to which the channel is connected
  482. * @param channel File channel of the database. This needs to be a
  483. * FileChannel instead of a ReadableByteChannel because we need to
  484. * randomly jump around to various points in the file.
  485. * @param autoSync whether or not to enable auto-syncing on write. if
  486. * {@code true}, writes will be immediately flushed to disk.
  487. * This leaves the database in a (fairly) consistent state
  488. * on each write, but can be very inefficient for many
  489. * updates. if {@code false}, flushing to disk happens at
  490. * the jvm's leisure, which can be much faster, but may
  491. * leave the database in an inconsistent state if failures
  492. * are encountered during writing. Writes may be flushed at
  493. * any time using {@link #flush}.
  494. * @param fileFormat version of new database (if known)
  495. * @param charset Charset to use, if {@code null}, uses default
  496. * @param timeZone TimeZone to use, if {@code null}, uses default
  497. */
  498. protected DatabaseImpl(Path file, FileChannel channel, boolean closeChannel,
  499. boolean autoSync, FileFormat fileFormat, Charset charset,
  500. TimeZone timeZone, CodecProvider provider,
  501. boolean readOnly)
  502. throws IOException
  503. {
  504. _file = file;
  505. _name = getName(file);
  506. _readOnly = readOnly;
  507. _format = JetFormat.getFormat(channel);
  508. _charset = ((charset == null) ? getDefaultCharset(_format) : charset);
  509. _columnOrder = getDefaultColumnOrder();
  510. _enforceForeignKeys = getDefaultEnforceForeignKeys();
  511. _allowAutoNumInsert = getDefaultAllowAutoNumberInsert();
  512. _evaluateExpressions = getDefaultEvaluateExpressions();
  513. _fileFormat = fileFormat;
  514. setZoneInfo(timeZone, null);
  515. _dtf = ColumnImpl.getDateTimeFactory(getDefaultDateTimeType());
  516. _pageChannel = new PageChannel(channel, closeChannel, _format, autoSync);
  517. if(provider == null) {
  518. provider = DefaultCodecProvider.INSTANCE;
  519. }
  520. // note, it's slighly sketchy to pass ourselves along partially
  521. // constructed, but only our _format and _pageChannel refs should be
  522. // needed
  523. _pageChannel.initialize(this, provider);
  524. _buffer = _pageChannel.createPageBuffer();
  525. readSystemCatalog();
  526. }
  527. @Override
  528. public File getFile() {
  529. return ((_file != null) ? _file.toFile() : null);
  530. }
  531. @Override
  532. public Path getPath() {
  533. return _file;
  534. }
  535. public String getName() {
  536. return _name;
  537. }
  538. public boolean isReadOnly() {
  539. return _readOnly;
  540. }
  541. /**
  542. * @usage _advanced_method_
  543. */
  544. public PageChannel getPageChannel() {
  545. return _pageChannel;
  546. }
  547. /**
  548. * @usage _advanced_method_
  549. */
  550. public JetFormat getFormat() {
  551. return _format;
  552. }
  553. /**
  554. * @return The system catalog table
  555. * @usage _advanced_method_
  556. */
  557. public TableImpl getSystemCatalog() {
  558. return _systemCatalog;
  559. }
  560. /**
  561. * @return The system Access Control Entries table (loaded on demand)
  562. * @usage _advanced_method_
  563. */
  564. public TableImpl getAccessControlEntries() throws IOException {
  565. if(_accessControlEntries == null) {
  566. _accessControlEntries = getRequiredSystemTable(TABLE_SYSTEM_ACES);
  567. }
  568. return _accessControlEntries;
  569. }
  570. /**
  571. * @return the complex column system table (loaded on demand)
  572. * @usage _advanced_method_
  573. */
  574. public TableImpl getSystemComplexColumns() throws IOException {
  575. if(_complexCols == null) {
  576. _complexCols = getRequiredSystemTable(TABLE_SYSTEM_COMPLEX_COLS);
  577. }
  578. return _complexCols;
  579. }
  580. @Override
  581. public ErrorHandler getErrorHandler() {
  582. return((_dbErrorHandler != null) ? _dbErrorHandler : ErrorHandler.DEFAULT);
  583. }
  584. @Override
  585. public void setErrorHandler(ErrorHandler newErrorHandler) {
  586. _dbErrorHandler = newErrorHandler;
  587. }
  588. @Override
  589. public LinkResolver getLinkResolver() {
  590. return((_linkResolver != null) ? _linkResolver : LinkResolver.DEFAULT);
  591. }
  592. @Override
  593. public void setLinkResolver(LinkResolver newLinkResolver) {
  594. _linkResolver = newLinkResolver;
  595. }
  596. @Override
  597. public Map<String,Database> getLinkedDatabases() {
  598. return ((_linkedDbs == null) ? Collections.<String,Database>emptyMap() :
  599. Collections.unmodifiableMap(_linkedDbs));
  600. }
  601. @Override
  602. public boolean isLinkedTable(Table table) throws IOException {
  603. if((table == null) || (this == table.getDatabase())) {
  604. // if the table is null or this db owns the table, not linked
  605. return false;
  606. }
  607. // common case, local table name == remote table name
  608. TableInfo tableInfo = lookupTable(table.getName());
  609. if((tableInfo != null) && tableInfo.isLinked() &&
  610. matchesLinkedTable(table, ((LinkedTableInfo)tableInfo).linkedTableName,
  611. ((LinkedTableInfo)tableInfo).linkedDbName)) {
  612. return true;
  613. }
  614. // but, the local table name may not match the remote table name, so we
  615. // need to do a search if the common case fails
  616. return _tableFinder.isLinkedTable(table);
  617. }
  618. private boolean matchesLinkedTable(Table table, String linkedTableName,
  619. String linkedDbName) {
  620. return (table.getName().equalsIgnoreCase(linkedTableName) &&
  621. (_linkedDbs != null) &&
  622. (_linkedDbs.get(linkedDbName) == table.getDatabase()));
  623. }
  624. @Override
  625. public TimeZone getTimeZone() {
  626. return _timeZone;
  627. }
  628. @Override
  629. public void setTimeZone(TimeZone newTimeZone) {
  630. setZoneInfo(newTimeZone, null);
  631. }
  632. @Override
  633. public ZoneId getZoneId() {
  634. return _zoneId;
  635. }
  636. @Override
  637. public void setZoneId(ZoneId newZoneId) {
  638. setZoneInfo(null, newZoneId);
  639. }
  640. private void setZoneInfo(TimeZone newTimeZone, ZoneId newZoneId) {
  641. if(newTimeZone != null) {
  642. newZoneId = newTimeZone.toZoneId();
  643. } else if(newZoneId != null) {
  644. newTimeZone = TimeZone.getTimeZone(newZoneId);
  645. } else {
  646. newTimeZone = getDefaultTimeZone();
  647. newZoneId = newTimeZone.toZoneId();
  648. }
  649. _timeZone = newTimeZone;
  650. _zoneId = newZoneId;
  651. }
  652. @Override
  653. public DateTimeType getDateTimeType() {
  654. return _dtf.getType();
  655. }
  656. @Override
  657. public void setDateTimeType(DateTimeType dateTimeType) {
  658. _dtf = ColumnImpl.getDateTimeFactory(dateTimeType);
  659. }
  660. @Override
  661. public ColumnImpl.DateTimeFactory getDateTimeFactory() {
  662. return _dtf;
  663. }
  664. @Override
  665. public Charset getCharset()
  666. {
  667. return _charset;
  668. }
  669. @Override
  670. public void setCharset(Charset newCharset) {
  671. if(newCharset == null) {
  672. newCharset = getDefaultCharset(getFormat());
  673. }
  674. _charset = newCharset;
  675. }
  676. @Override
  677. public Table.ColumnOrder getColumnOrder() {
  678. return _columnOrder;
  679. }
  680. @Override
  681. public void setColumnOrder(Table.ColumnOrder newColumnOrder) {
  682. if(newColumnOrder == null) {
  683. newColumnOrder = getDefaultColumnOrder();
  684. }
  685. _columnOrder = newColumnOrder;
  686. }
  687. @Override
  688. public boolean isEnforceForeignKeys() {
  689. return _enforceForeignKeys;
  690. }
  691. @Override
  692. public void setEnforceForeignKeys(Boolean newEnforceForeignKeys) {
  693. if(newEnforceForeignKeys == null) {
  694. newEnforceForeignKeys = getDefaultEnforceForeignKeys();
  695. }
  696. _enforceForeignKeys = newEnforceForeignKeys;
  697. }
  698. @Override
  699. public boolean isAllowAutoNumberInsert() {
  700. return _allowAutoNumInsert;
  701. }
  702. @Override
  703. public void setAllowAutoNumberInsert(Boolean allowAutoNumInsert) {
  704. if(allowAutoNumInsert == null) {
  705. allowAutoNumInsert = getDefaultAllowAutoNumberInsert();
  706. }
  707. _allowAutoNumInsert = allowAutoNumInsert;
  708. }
  709. @Override
  710. public boolean isEvaluateExpressions() {
  711. return _evaluateExpressions;
  712. }
  713. @Override
  714. public void setEvaluateExpressions(Boolean evaluateExpressions) {
  715. if(evaluateExpressions == null) {
  716. evaluateExpressions = getDefaultEvaluateExpressions();
  717. }
  718. _evaluateExpressions = evaluateExpressions;
  719. }
  720. @Override
  721. public ColumnValidatorFactory getColumnValidatorFactory() {
  722. return _validatorFactory;
  723. }
  724. @Override
  725. public void setColumnValidatorFactory(ColumnValidatorFactory newFactory) {
  726. if(newFactory == null) {
  727. newFactory = SimpleColumnValidatorFactory.INSTANCE;
  728. }
  729. _validatorFactory = newFactory;
  730. }
  731. /**
  732. * @usage _advanced_method_
  733. */
  734. FKEnforcer.SharedState getFKEnforcerSharedState() {
  735. return _fkEnforcerSharedState;
  736. }
  737. @Override
  738. public EvalConfig getEvalConfig() {
  739. return getEvalContext();
  740. }
  741. /**
  742. * @usage _advanced_method_
  743. */
  744. DBEvalContext getEvalContext() {
  745. if(_evalCtx == null) {
  746. _evalCtx = new DBEvalContext(this);
  747. }
  748. return _evalCtx;
  749. }
  750. /**
  751. * Returns a SimpleDateFormat for the given format string which is
  752. * configured with a compatible Calendar instance (see
  753. * {@link DatabaseBuilder#toCompatibleCalendar}) and this database's
  754. * {@link TimeZone}.
  755. */
  756. public SimpleDateFormat createDateFormat(String formatStr) {
  757. SimpleDateFormat sdf = DatabaseBuilder.createDateFormat(formatStr);
  758. sdf.setTimeZone(getTimeZone());
  759. return sdf;
  760. }
  761. /**
  762. * @returns the current handler for reading/writing properties, creating if
  763. * necessary
  764. */
  765. private PropertyMaps.Handler getPropsHandler() {
  766. if(_propsHandler == null) {
  767. _propsHandler = new PropertyMaps.Handler(this);
  768. }
  769. return _propsHandler;
  770. }
  771. @Override
  772. public FileFormat getFileFormat() throws IOException {
  773. if(_fileFormat == null) {
  774. Map<String,FileFormat> possibleFileFormats =
  775. getFormat().getPossibleFileFormats();
  776. if(possibleFileFormats.size() == 1) {
  777. // single possible format (null key), easy enough
  778. _fileFormat = possibleFileFormats.get(null);
  779. } else {
  780. // need to check the "AccessVersion" property
  781. String accessVersion = (String)getDatabaseProperties().getValue(
  782. PropertyMap.ACCESS_VERSION_PROP);
  783. if(isBlank(accessVersion)) {
  784. // no access version, fall back to "generic"
  785. accessVersion = null;
  786. }
  787. _fileFormat = possibleFileFormats.get(accessVersion);
  788. if(_fileFormat == null) {
  789. throw new IllegalStateException(withErrorContext(
  790. "Could not determine FileFormat"));
  791. }
  792. }
  793. }
  794. return _fileFormat;
  795. }
  796. /**
  797. * @return a (possibly cached) page ByteBuffer for internal use. the
  798. * returned buffer should be released using
  799. * {@link #releaseSharedBuffer} when no longer in use
  800. */
  801. private ByteBuffer takeSharedBuffer() {
  802. // we try to re-use a single shared _buffer, but occassionally, it may be
  803. // needed by multiple operations at the same time (e.g. loading a
  804. // secondary table while loading a primary table). this method ensures
  805. // that we don't corrupt the _buffer, but instead force the second caller
  806. // to use a new buffer.
  807. if(_buffer != null) {
  808. ByteBuffer curBuffer = _buffer;
  809. _buffer = null;
  810. return curBuffer;
  811. }
  812. return _pageChannel.createPageBuffer();
  813. }
  814. /**
  815. * Relinquishes use of a page ByteBuffer returned by
  816. * {@link #takeSharedBuffer}.
  817. */
  818. private void releaseSharedBuffer(ByteBuffer buffer) {
  819. // we always stuff the returned buffer back into _buffer. it doesn't
  820. // really matter if multiple values over-write, at the end of the day, we
  821. // just need one shared buffer
  822. _buffer = buffer;
  823. }
  824. /**
  825. * @return the currently configured database default language sort order for
  826. * textual columns
  827. * @usage _intermediate_method_
  828. */
  829. public ColumnImpl.SortOrder getDefaultSortOrder() throws IOException {
  830. if(_defaultSortOrder == null) {
  831. initRootPageInfo();
  832. }
  833. return _defaultSortOrder;
  834. }
  835. /**
  836. * @return the currently configured database default code page for textual
  837. * data (may not be relevant to all database versions)
  838. * @usage _intermediate_method_
  839. */
  840. public short getDefaultCodePage() throws IOException {
  841. if(_defaultCodePage == null) {
  842. initRootPageInfo();
  843. }
  844. return _defaultCodePage;
  845. }
  846. /**
  847. * Reads various config info from the db page 0.
  848. */
  849. private void initRootPageInfo() throws IOException {
  850. ByteBuffer buffer = takeSharedBuffer();
  851. try {
  852. _pageChannel.readRootPage(buffer);
  853. _defaultSortOrder = ColumnImpl.readSortOrder(
  854. buffer, _format.OFFSET_SORT_ORDER, _format);
  855. _defaultCodePage = buffer.getShort(_format.OFFSET_CODE_PAGE);
  856. } finally {
  857. releaseSharedBuffer(buffer);
  858. }
  859. }
  860. /**
  861. * @return a PropertyMaps instance decoded from the given bytes (always
  862. * returns non-{@code null} result).
  863. * @usage _intermediate_method_
  864. */
  865. public PropertyMaps readProperties(byte[] propsBytes, int objectId,
  866. RowIdImpl rowId)
  867. throws IOException
  868. {
  869. return getPropsHandler().read(propsBytes, objectId, rowId, null);
  870. }
  871. /**
  872. * Read the system catalog
  873. */
  874. private void readSystemCatalog() throws IOException {
  875. _systemCatalog = readTable(TABLE_SYSTEM_CATALOG, PAGE_SYSTEM_CATALOG,
  876. SYSTEM_OBJECT_FLAGS);
  877. try {
  878. _tableFinder = new DefaultTableFinder(
  879. _systemCatalog.newCursor()
  880. .setIndexByColumnNames(CAT_COL_PARENT_ID, CAT_COL_NAME)
  881. .setColumnMatcher(CaseInsensitiveColumnMatcher.INSTANCE)
  882. .toIndexCursor());
  883. } catch(IllegalArgumentException e) {
  884. if(LOG.isDebugEnabled()) {
  885. LOG.debug(withErrorContext(
  886. "Could not find expected index on table " +
  887. _systemCatalog.getName()));
  888. }
  889. // use table scan instead
  890. _tableFinder = new FallbackTableFinder(
  891. _systemCatalog.newCursor()
  892. .setColumnMatcher(CaseInsensitiveColumnMatcher.INSTANCE)
  893. .toCursor());
  894. }
  895. _tableParentId = _tableFinder.findObjectId(DB_PARENT_ID,
  896. SYSTEM_OBJECT_NAME_TABLES);
  897. if(_tableParentId == null) {
  898. throw new IOException(withErrorContext(
  899. "Did not find required parent table id"));
  900. }
  901. if (LOG.isDebugEnabled()) {
  902. LOG.debug(withErrorContext(
  903. "Finished reading system catalog. Tables: " + getTableNames()));
  904. }
  905. }
  906. @Override
  907. public Set<String> getTableNames() throws IOException {
  908. if(_tableNames == null) {
  909. _tableNames = getTableNames(true, false, true);
  910. }
  911. return _tableNames;
  912. }
  913. @Override
  914. public Set<String> getSystemTableNames() throws IOException {
  915. return getTableNames(false, true, false);
  916. }
  917. private Set<String> getTableNames(boolean normalTables, boolean systemTables,
  918. boolean linkedTables)
  919. throws IOException
  920. {
  921. Set<String> tableNames = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
  922. _tableFinder.getTableNames(tableNames, normalTables, systemTables,
  923. linkedTables);
  924. return tableNames;
  925. }
  926. @Override
  927. public Iterator<Table> iterator() {
  928. try {
  929. return new TableIterator(getTableNames());
  930. } catch(IOException e) {
  931. throw new RuntimeIOException(e);
  932. }
  933. }
  934. public Iterator<Table> iterator(TableIterableBuilder builder) {
  935. try {
  936. return new TableIterator(getTableNames(builder.isIncludeNormalTables(),
  937. builder.isIncludeSystemTables(),
  938. builder.isIncludeLinkedTables()));
  939. } catch(IOException e) {
  940. throw new RuntimeIOException(e);
  941. }
  942. }
  943. @Override
  944. public TableIterableBuilder newIterable() {
  945. return new TableIterableBuilder(this);
  946. }
  947. @Override
  948. public Iterable<TableMetaData> newTableMetaDataIterable() {
  949. return new Iterable<TableMetaData>() {
  950. @Override
  951. public Iterator<TableMetaData> iterator() {
  952. try {
  953. return _tableFinder.iterateTableMetaData();
  954. } catch(IOException e) {
  955. throw new RuntimeIOException(e);
  956. }
  957. }
  958. };
  959. }
  960. @Override
  961. public TableImpl getTable(String name) throws IOException {
  962. return getTable(name, false);
  963. }
  964. @Override
  965. public TableMetaData getTableMetaData(String name) throws IOException {
  966. return getTableInfo(name, true);
  967. }
  968. /**
  969. * @param tableDefPageNumber the page number of a table definition
  970. * @return The table, or null if it doesn't exist
  971. * @usage _advanced_method_
  972. */
  973. public TableImpl getTable(int tableDefPageNumber) throws IOException {
  974. // first, check for existing table
  975. TableImpl table = _tableCache.get(tableDefPageNumber);
  976. if(table != null) {
  977. return table;
  978. }
  979. // lookup table info from system catalog
  980. Row objectRow = _tableFinder.getObjectRow(
  981. tableDefPageNumber, SYSTEM_CATALOG_COLUMNS);
  982. if(objectRow == null) {
  983. return null;
  984. }
  985. String name = objectRow.getString(CAT_COL_NAME);
  986. int flags = objectRow.getInt(CAT_COL_FLAGS);
  987. return readTable(name, tableDefPageNumber, flags);
  988. }
  989. /**
  990. * @param name Table name
  991. * @param includeSystemTables whether to consider returning a system table
  992. * @return The table, or null if it doesn't exist
  993. */
  994. protected TableImpl getTable(String name, boolean includeSystemTables)
  995. throws IOException
  996. {
  997. TableInfo tableInfo = getTableInfo(name, includeSystemTables);
  998. return ((tableInfo != null) ?
  999. getTable(tableInfo, includeSystemTables) : null);
  1000. }
  1001. private TableInfo getTableInfo(String name, boolean includeSystemTables)
  1002. throws IOException
  1003. {
  1004. TableInfo tableInfo = lookupTable(name);
  1005. if ((tableInfo == null) || (tableInfo.pageNumber == null)) {
  1006. return null;
  1007. }
  1008. if(!includeSystemTables && tableInfo.isSystem()) {
  1009. return null;
  1010. }
  1011. return tableInfo;
  1012. }
  1013. private TableImpl getTable(TableInfo tableInfo, boolean includeSystemTables)
  1014. throws IOException
  1015. {
  1016. if(tableInfo.isLinked()) {
  1017. if(_linkedDbs == null) {
  1018. _linkedDbs = new HashMap<String,Database>();
  1019. }
  1020. String linkedDbName = ((LinkedTableInfo)tableInfo).linkedDbName;
  1021. String linkedTableName = ((LinkedTableInfo)tableInfo).linkedTableName;
  1022. Database linkedDb = _linkedDbs.get(linkedDbName);
  1023. if(linkedDb == null) {
  1024. linkedDb = getLinkResolver().resolveLinkedDatabase(this, linkedDbName);
  1025. _linkedDbs.put(linkedDbName, linkedDb);
  1026. }
  1027. return ((DatabaseImpl)linkedDb).getTable(linkedTableName,
  1028. includeSystemTables);
  1029. }
  1030. return readTable(tableInfo.tableName, tableInfo.pageNumber,
  1031. tableInfo.flags);
  1032. }
  1033. /**
  1034. * Create a new table in this database
  1035. * @param name Name of the table to create
  1036. * @param columns List of Columns in the table
  1037. * @deprecated use {@link TableBuilder} instead
  1038. */
  1039. @Deprecated
  1040. public void createTable(String name, List<ColumnBuilder> columns)
  1041. throws IOException
  1042. {
  1043. createTable(name, columns, null);
  1044. }
  1045. /**
  1046. * Create a new table in this database
  1047. * @param name Name of the table to create
  1048. * @param columns List of Columns in the table
  1049. * @param indexes List of IndexBuilders describing indexes for the table
  1050. * @deprecated use {@link TableBuilder} instead
  1051. */
  1052. @Deprecated
  1053. public void createTable(String name, List<ColumnBuilder> columns,
  1054. List<IndexBuilder> indexes)
  1055. throws IOException
  1056. {
  1057. new TableBuilder(name)
  1058. .addColumns(columns)
  1059. .addIndexes(indexes)
  1060. .toTable(this);
  1061. }
  1062. @Override
  1063. public void createLinkedTable(String name, String linkedDbName,
  1064. String linkedTableName)
  1065. throws IOException
  1066. {
  1067. if(lookupTable(name) != null) {
  1068. throw new IllegalArgumentException(withErrorContext(
  1069. "Cannot create linked table with name of existing table '" + name +
  1070. "'"));
  1071. }
  1072. validateIdentifierName(name, getFormat().MAX_TABLE_NAME_LENGTH, "table");
  1073. validateName(linkedDbName, DataType.MEMO.getMaxSize(),
  1074. "linked database");
  1075. validateIdentifierName(linkedTableName, getFormat().MAX_TABLE_NAME_LENGTH,
  1076. "linked table");
  1077. getPageChannel().startWrite();
  1078. try {
  1079. int linkedTableId = _tableFinder.getNextFreeSyntheticId();
  1080. addNewTable(name, linkedTableId, TYPE_LINKED_TABLE, linkedDbName,
  1081. linkedTableName);
  1082. } finally {
  1083. getPageChannel().finishWrite();
  1084. }
  1085. }
  1086. /**
  1087. * Adds a newly created table to the relevant internal database structures.
  1088. */
  1089. void addNewTable(String name, int tdefPageNumber, Short type,
  1090. String linkedDbName, String linkedTableName)
  1091. throws IOException
  1092. {
  1093. //Add this table to our internal list.
  1094. addTable(name, Integer.valueOf(tdefPageNumber), type, linkedDbName,
  1095. linkedTableName);
  1096. //Add this table to system tables
  1097. addToSystemCatalog(name, tdefPageNumber, type, linkedDbName,
  1098. linkedTableName, _tableParentId);
  1099. addToAccessControlEntries(tdefPageNumber, _tableParentId, _newTableSIDs);
  1100. }
  1101. @Override
  1102. public List<Relationship> getRelationships(Table table1, Table table2)
  1103. throws IOException
  1104. {
  1105. return getRelationships((TableImpl)table1, (TableImpl)table2);
  1106. }
  1107. public List<Relationship> getRelationships(
  1108. TableImpl table1, TableImpl table2)
  1109. throws IOException
  1110. {
  1111. int nameCmp = table1.getName().compareTo(table2.getName());
  1112. if(nameCmp == 0) {
  1113. throw new IllegalArgumentException(withErrorContext(
  1114. "Must provide two different tables"));
  1115. }
  1116. if(nameCmp > 0) {
  1117. // we "order" the two tables given so that we will return a collection
  1118. // of relationships in the same order regardless of whether we are given
  1119. // (TableFoo, TableBar) or (TableBar, TableFoo).
  1120. TableImpl tmp = table1;
  1121. table1 = table2;
  1122. table2 = tmp;
  1123. }
  1124. return getRelationshipsImpl(table1, table2, true);
  1125. }
  1126. @Override
  1127. public List<Relationship> getRelationships(Table table)
  1128. throws IOException
  1129. {
  1130. if(table == null) {
  1131. throw new IllegalArgumentException(withErrorContext("Must provide a table"));
  1132. }
  1133. // since we are getting relationships specific to certain table include
  1134. // all tables
  1135. return getRelationshipsImpl((TableImpl)table, null, true);
  1136. }
  1137. @Override
  1138. public List<Relationship> getRelationships()
  1139. throws IOException
  1140. {
  1141. return getRelationshipsImpl(null, null, false);
  1142. }
  1143. @Override
  1144. public List<Relationship> getSystemRelationships()
  1145. throws IOException
  1146. {
  1147. return getRelationshipsImpl(null, null, true);
  1148. }
  1149. private List<Relationship> getRelationshipsImpl(
  1150. TableImpl table1, TableImpl table2, boolean includeSystemTables)
  1151. throws IOException
  1152. {
  1153. initRelationships();
  1154. List<Relationship> relationships = new ArrayList<Relationship>();
  1155. if(table1 != null) {
  1156. Cursor cursor = createCursorWithOptionalIndex(
  1157. _relationships, REL_COL_FROM_TABLE, table1.getName());
  1158. collectRelationships(cursor, table1, table2, relationships,
  1159. includeSystemTables);
  1160. cursor = createCursorWithOptionalIndex(
  1161. _relationships, REL_COL_TO_TABLE, table1.getName());
  1162. collectRelationships(cursor, table2, table1, relationships,
  1163. includeSystemTables);
  1164. } else {
  1165. collectRelationships(new CursorBuilder(_relationships).toCursor(),
  1166. null, null, relationships, includeSystemTables);
  1167. }
  1168. return relationships;
  1169. }
  1170. RelationshipImpl writeRelationship(RelationshipCreator creator)
  1171. throws IOException
  1172. {
  1173. initRelationships();
  1174. String name = createRelationshipName(creator);
  1175. RelationshipImpl newRel = creator.createRelationshipImpl(name);
  1176. ColumnImpl ccol = _relationships.getColumn(REL_COL_COLUMN_COUNT);
  1177. ColumnImpl flagCol = _relationships.getColumn(REL_COL_FLAGS);
  1178. ColumnImpl icol = _relationships.getColumn(REL_COL_COLUMN_INDEX);
  1179. ColumnImpl nameCol = _relationships.getColumn(REL_COL_NAME);
  1180. ColumnImpl fromTableCol = _relationships.getColumn(REL_COL_FROM_TABLE);
  1181. ColumnImpl fromColCol = _relationships.getColumn(REL_COL_FROM_COLUMN);
  1182. ColumnImpl toTableCol = _relationships.getColumn(REL_COL_TO_TABLE);
  1183. ColumnImpl toColCol = _relationships.getColumn(REL_COL_TO_COLUMN);
  1184. int numCols = newRel.getFromColumns().size();
  1185. List<Object[]> rows = new ArrayList<Object[]>(numCols);
  1186. for(int i = 0; i < numCols; ++i) {
  1187. Object[] row = new Object[_relationships.getColumnCount()];
  1188. ccol.setRowValue(row, numCols);
  1189. flagCol.setRowValue(row, newRel.getFlags());
  1190. icol.setRowValue(row, i);
  1191. nameCol.setRowValue(row, name);
  1192. fromTableCol.setRowValue(row, newRel.getFromTable().getName());
  1193. fromColCol.setRowValue(row, newRel.getFromColumns().get(i).getName());
  1194. toTableCol.setRowValue(row, newRel.getToTable().getName());
  1195. toColCol.setRowValue(row, newRel.getToColumns().get(i).getName());
  1196. rows.add(row);
  1197. }
  1198. getPageChannel().startWrite();
  1199. try {
  1200. int relObjId = _tableFinder.getNextFreeSyntheticId();
  1201. _relationships.addRows(rows);
  1202. addToSystemCatalog(name, relObjId, TYPE_RELATIONSHIP, null, null,
  1203. _relParentId);
  1204. addToAccessControlEntries(relObjId, _relParentId, _newRelSIDs);
  1205. } finally {
  1206. getPageChannel().finishWrite();
  1207. }
  1208. return newRel;
  1209. }
  1210. private void initRelationships() throws IOException {
  1211. // the relationships table does not get loaded until first accessed
  1212. if(_relationships == null) {
  1213. // need the parent id of the relationships objects
  1214. _relParentId = _tableFinder.findObjectId(DB_PARENT_ID,
  1215. SYSTEM_OBJECT_NAME_RELATIONSHIPS);
  1216. _relationships = getRequiredSystemTable(TABLE_SYSTEM_RELATIONSHIPS);
  1217. }
  1218. }
  1219. private String createRelationshipName(RelationshipCreator creator)
  1220. throws IOException
  1221. {
  1222. // ensure that the final identifier name does not get too long
  1223. // - the primary name is limited to ((max / 2) - 3)
  1224. // - the total name is limited to (max - 3)
  1225. int maxIdLen = getFormat().MAX_INDEX_NAME_LENGTH;
  1226. int limit = (maxIdLen / 2) - 3;
  1227. String origName = creator.getName();
  1228. if (origName == null) {
  1229. origName = creator.getPrimaryTable().getName();
  1230. if(origName.length() > limit) {
  1231. origName = origName.substring(0, limit);
  1232. }
  1233. origName += creator.getSecondaryTable().getName();
  1234. }
  1235. limit = maxIdLen - 3;
  1236. if(origName.length() > limit) {
  1237. origName = origName.substring(0, limit);
  1238. }
  1239. // now ensure name is unique
  1240. Set<String> names = new HashSet<String>();
  1241. // collect the names of all relationships for uniqueness check
  1242. for(Row row :
  1243. CursorImpl.createCursor(_systemCatalog).newIterable().setColumnNames(
  1244. SYSTEM_CATALOG_COLUMNS))
  1245. {
  1246. String name = row.getString(CAT_COL_NAME);
  1247. if (name != null && TYPE_RELATIONSHIP.equals(row.get(CAT_COL_TYPE))) {
  1248. names.add(toLookupName(name));
  1249. }
  1250. }
  1251. if(creator.hasReferentialIntegrity()) {
  1252. // relationship name will also be index name in secondary table, so must
  1253. // check those names as well
  1254. for(Index idx : creator.getSecondaryTable().getIndexes()) {
  1255. names.add(toLookupName(idx.getName()));
  1256. }
  1257. }
  1258. String baseName = toLookupName(origName);
  1259. String name = baseName;
  1260. int i = 0;
  1261. while(names.contains(name)) {
  1262. name = baseName + (++i);
  1263. }
  1264. return ((i == 0) ? origName : (origName + i));
  1265. }
  1266. @Override
  1267. public List<Query> getQueries() throws IOException
  1268. {
  1269. // the queries table does not get loaded until first accessed
  1270. if(_queries == null) {
  1271. _queries = getRequiredSystemTable(TABLE_SYSTEM_QUERIES);
  1272. }
  1273. // find all the queries from the system catalog
  1274. List<Row> queryInfo = new ArrayList<Row>();
  1275. Map<Integer,List<QueryImpl.Row>> queryRowMap =
  1276. new HashMap<Integer,List<QueryImpl.Row>>();
  1277. for(Row row :
  1278. CursorImpl.createCursor(_systemCatalog).newIterable().setColumnNames(
  1279. SYSTEM_CATALOG_COLUMNS))
  1280. {
  1281. String name = row.getString(CAT_COL_NAME);
  1282. if (name != null && TYPE_QUERY.equals(row.get(CAT_COL_TYPE))) {
  1283. queryInfo.add(row);
  1284. Integer id = row.getInt(CAT_COL_ID);
  1285. queryRowMap.put(id, new ArrayList<QueryImpl.Row>());
  1286. }
  1287. }
  1288. // find all the query rows
  1289. for(Row row : CursorImpl.createCursor(_queries)) {
  1290. QueryImpl.Row queryRow = new QueryImpl.Row(row);
  1291. List<QueryImpl.Row> queryRows = queryRowMap.get(queryRow.objectId);
  1292. if(queryRows == null) {
  1293. LOG.warn(withErrorContext(
  1294. "Found rows for query with id " + queryRow.objectId +
  1295. " missing from system catalog"));
  1296. continue;
  1297. }
  1298. queryRows.add(queryRow);
  1299. }
  1300. // lastly, generate all the queries
  1301. List<Query> queries = new ArrayList<Query>();
  1302. for(Row row : queryInfo) {
  1303. String name = row.getString(CAT_COL_NAME);
  1304. Integer id = row.getInt(CAT_COL_ID);
  1305. int flags = row.getInt(CAT_COL_FLAGS);
  1306. List<QueryImpl.Row> queryRows = queryRowMap.get(id);
  1307. queries.add(QueryImpl.create(flags, name, queryRows, id));
  1308. }
  1309. return queries;
  1310. }
  1311. @Override
  1312. public TableImpl getSystemTable(String tableName) throws IOException
  1313. {
  1314. return getTable(tableName, true);
  1315. }
  1316. private TableImpl getRequiredSystemTable(String tableName) throws IOException
  1317. {
  1318. TableImpl table = getSystemTable(tableName);
  1319. if(table == null) {
  1320. throw new IOException(withErrorContext(
  1321. "Could not find system table " + tableName));
  1322. }
  1323. return table;
  1324. }
  1325. @Override
  1326. public PropertyMap getDatabaseProperties() throws IOException {
  1327. if(_dbPropMaps == null) {
  1328. _dbPropMaps = getPropertiesForDbObject(OBJECT_NAME_DB_PROPS);
  1329. }
  1330. return _dbPropMaps.getDefault();
  1331. }
  1332. @Override
  1333. public PropertyMap getSummaryProperties() throws IOException {
  1334. if(_summaryPropMaps == null) {
  1335. _summaryPropMaps = getPropertiesForDbObject(OBJECT_NAME_SUMMARY_PROPS);
  1336. }
  1337. return _summaryPropMaps.getDefault();
  1338. }
  1339. @Override
  1340. public PropertyMap getUserDefinedProperties() throws IOException {
  1341. if(_userDefPropMaps == null) {
  1342. _userDefPropMaps = getPropertiesForDbObject(OBJECT_NAME_USERDEF_PROPS);
  1343. }
  1344. return _userDefPropMaps.getDefault();
  1345. }
  1346. /**
  1347. * @return the PropertyMaps for the object with the given id
  1348. * @usage _advanced_method_
  1349. */
  1350. public PropertyMaps getPropertiesForObject(
  1351. int objectId, PropertyMaps.Owner owner)
  1352. throws IOException
  1353. {
  1354. return readProperties(
  1355. objectId, _tableFinder.getObjectRow(
  1356. objectId, SYSTEM_CATALOG_PROPS_COLUMNS), owner);
  1357. }
  1358. private Integer getDbParentId() throws IOException {
  1359. if(_dbParentId == null) {
  1360. // need the parent id of the databases objects
  1361. _dbParentId = _tableFinder.findObjectId(DB_PARENT_ID,
  1362. SYSTEM_OBJECT_NAME_DATABASES);
  1363. if(_dbParentId == null) {
  1364. throw new IOException(withErrorContext(
  1365. "Did not find required parent db id"));
  1366. }
  1367. }
  1368. return _dbParentId;
  1369. }
  1370. private byte[] getNewObjectOwner() throws IOException {
  1371. if(_newObjOwner == null) {
  1372. // there doesn't seem to be any obvious way to find the main "owner" of
  1373. // an access db, but certain db objects seem to have the common db
  1374. // owner. we attempt to grab the db properties object and use its
  1375. // owner.
  1376. Row msysDbRow = _tableFinder.getObjectRow(
  1377. getDbParentId(), OBJECT_NAME_DB_PROPS,
  1378. Collections.singleton(CAT_COL_OWNER));
  1379. byte[] owner = null;
  1380. if(msysDbRow != null) {
  1381. owner = msysDbRow.getBytes(CAT_COL_OWNER);
  1382. }
  1383. _newObjOwner = (((owner != null) && (owner.length > 0)) ?
  1384. owner : SYS_DEFAULT_SID);
  1385. }
  1386. return _newObjOwner;
  1387. }
  1388. /**
  1389. * @return property group for the given "database" object
  1390. */
  1391. private PropertyMaps getPropertiesForDbObject(String dbName)
  1392. throws IOException
  1393. {
  1394. return readProperties(
  1395. -1, _tableFinder.getObjectRow(
  1396. getDbParentId(), dbName, SYSTEM_CATALOG_PROPS_COLUMNS), null);
  1397. }
  1398. private PropertyMaps readProperties(int objectId, Row objectRow,
  1399. PropertyMaps.Owner owner)
  1400. throws IOException
  1401. {
  1402. byte[] propsBytes = null;
  1403. RowIdImpl rowId = null;
  1404. if(objectRow != null) {
  1405. propsBytes = objectRow.getBytes(CAT_COL_PROPS);
  1406. objectId = objectRow.getInt(CAT_COL_ID);
  1407. rowId = (RowIdImpl)objectRow.getId();
  1408. }
  1409. return getPropsHandler().read(propsBytes, objectId, rowId, owner);
  1410. }
  1411. @Override
  1412. public String getDatabasePassword() throws IOException
  1413. {
  1414. ByteBuffer buffer = takeSharedBuffer();
  1415. try {
  1416. _pageChannel.readRootPage(buffer);
  1417. byte[] pwdBytes = new byte[_format.SIZE_PASSWORD];
  1418. buffer.position(_format.OFFSET_PASSWORD);
  1419. buffer.get(pwdBytes);
  1420. // de-mask password using extra password mask if necessary (the extra
  1421. // password mask is generated from the database creation date stored in
  1422. // the header)
  1423. byte[] pwdMask = getPasswordMask(buffer, _format);
  1424. if(pwdMask != null) {
  1425. for(int i = 0; i < pwdBytes.length; ++i) {
  1426. pwdBytes[i] ^= pwdMask[i % pwdMask.length];
  1427. }
  1428. }
  1429. boolean hasPassword = false;
  1430. for(int i = 0; i < pwdBytes.length; ++i) {
  1431. if(pwdBytes[i] != 0) {
  1432. hasPassword = true;
  1433. break;
  1434. }
  1435. }
  1436. if(!hasPassword) {
  1437. return null;
  1438. }
  1439. String pwd = ColumnImpl.decodeUncompressedText(pwdBytes, getCharset());
  1440. // remove any trailing null chars
  1441. int idx = pwd.indexOf('\0');
  1442. if(idx >= 0) {
  1443. pwd = pwd.substring(0, idx);
  1444. }
  1445. return pwd;
  1446. } finally {
  1447. releaseSharedBuffer(buffer);
  1448. }
  1449. }
  1450. /**
  1451. * Finds the relationships matching the given from and to tables from the
  1452. * given cursor and adds them to the given list.
  1453. */
  1454. private void collectRelationships(
  1455. Cursor cursor, TableImpl fromTable, TableImpl toTable,
  1456. List<Relationship> relationships, boolean includeSystemTables)
  1457. throws IOException
  1458. {
  1459. String fromTableName = ((fromTable != null) ? fromTable.getName() : null);
  1460. String toTableName = ((toTable != null) ? toTable.getName() : null);
  1461. for(Row row : cursor) {
  1462. String fromName = row.getString(REL_COL_FROM_TABLE);
  1463. String toName = row.getString(REL_COL_TO_TABLE);
  1464. if(((fromTableName == null) ||
  1465. fromTableName.equalsIgnoreCase(fromName)) &&
  1466. ((toTableName == null) ||
  1467. toTableName.equalsIgnoreCase(toName))) {
  1468. String relName = row.getString(REL_COL_NAME);
  1469. // found more info for a relationship. see if we already have some
  1470. // info for this relationship
  1471. Relationship rel = null;
  1472. for(Relationship tmp : relationships) {
  1473. if(tmp.getName().equalsIgnoreCase(relName)) {
  1474. rel = tmp;
  1475. break;
  1476. }
  1477. }
  1478. TableImpl relFromTable = fromTable;
  1479. if(relFromTable == null) {
  1480. relFromTable = getTable(fromName, includeSystemTables);
  1481. if(relFromTable == null) {
  1482. // invalid table or ignoring system tables, just ignore
  1483. continue;
  1484. }
  1485. }
  1486. TableImpl relToTable = toTable;
  1487. if(relToTable == null) {
  1488. relToTable = getTable(toName, includeSystemTables);
  1489. if(relToTable == null) {
  1490. // invalid table or ignoring system tables, just ignore
  1491. continue;
  1492. }
  1493. }
  1494. if(rel == null) {
  1495. // new relationship
  1496. int numCols = row.getInt(REL_COL_COLUMN_COUNT);
  1497. int flags = row.getInt(REL_COL_FLAGS);
  1498. rel = new RelationshipImpl(relName, relFromTable, relToTable,
  1499. flags, numCols);
  1500. relationships.add(rel);
  1501. }
  1502. // add column info
  1503. int colIdx = row.getInt(REL_COL_COLUMN_INDEX);
  1504. ColumnImpl fromCol = relFromTable.getColumn(
  1505. row.getString(REL_COL_FROM_COLUMN));
  1506. ColumnImpl toCol = relToTable.getColumn(
  1507. row.getString(REL_COL_TO_COLUMN));
  1508. rel.getFromColumns().set(colIdx, fromCol);
  1509. rel.getToColumns().set(colIdx, toCol);
  1510. }
  1511. }
  1512. }
  1513. /**
  1514. * Add a new table to the system catalog
  1515. * @param name Table name
  1516. * @param objectId id of the new object
  1517. */
  1518. private void addToSystemCatalog(String name, int objectId, Short type,
  1519. String linkedDbName, String linkedTableName,
  1520. Integer parentId)
  1521. throws IOException
  1522. {
  1523. byte[] owner = getNewObjectOwner();
  1524. Object[] catalogRow = new Object[_systemCatalog.getColumnCount()];
  1525. int idx = 0;
  1526. Date creationTime = new Date();
  1527. for (Iterator<ColumnImpl> iter = _systemCatalog.getColumns().iterator();
  1528. iter.hasNext(); idx++)
  1529. {
  1530. ColumnImpl col = iter.next();
  1531. if (CAT_COL_ID.equals(col.getName())) {
  1532. catalogRow[idx] = Integer.valueOf(objectId);
  1533. } else if (CAT_COL_NAME.equals(col.getName())) {
  1534. catalogRow[idx] = name;
  1535. } else if (CAT_COL_TYPE.equals(col.getName())) {
  1536. catalogRow[idx] = type;
  1537. } else if (CAT_COL_DATE_CREATE.equals(col.getName()) ||
  1538. CAT_COL_DATE_UPDATE.equals(col.getName())) {
  1539. catalogRow[idx] = creationTime;
  1540. } else if (CAT_COL_PARENT_ID.equals(col.getName())) {
  1541. catalogRow[idx] = parentId;
  1542. } else if (CAT_COL_FLAGS.equals(col.getName())) {
  1543. catalogRow[idx] = Integer.valueOf(0);
  1544. } else if (CAT_COL_OWNER.equals(col.getName())) {
  1545. catalogRow[idx] = owner;
  1546. } else if (CAT_COL_DATABASE.equals(col.getName())) {
  1547. catalogRow[idx] = linkedDbName;
  1548. } else if (CAT_COL_FOREIGN_NAME.equals(col.getName())) {
  1549. catalogRow[idx] = linkedTableName;
  1550. }
  1551. }
  1552. _systemCatalog.addRow(catalogRow);
  1553. }
  1554. /**
  1555. * Adds a new object to the system's access control entries
  1556. */
  1557. private void addToAccessControlEntries(
  1558. Integer objectId, Integer parentId, List<byte[]> sids)
  1559. throws IOException
  1560. {
  1561. if(sids.isEmpty()) {
  1562. collectNewObjectSIDs(parentId, sids);
  1563. }
  1564. TableImpl acEntries = getAccessControlEntries();
  1565. ColumnImpl acmCol = acEntries.getColumn(ACE_COL_ACM);
  1566. ColumnImpl inheritCol = acEntries.getColumn(ACE_COL_F_INHERITABLE);
  1567. ColumnImpl objIdCol = acEntries.getColumn(ACE_COL_OBJECT_ID);
  1568. ColumnImpl sidCol = acEntries.getColumn(ACE_COL_SID);
  1569. // construct a collection of ACE entries
  1570. List<Object[]> aceRows = new ArrayList<Object[]>(sids.size());
  1571. for(byte[] sid : sids) {
  1572. Object[] aceRow = new Object[acEntries.getColumnCount()];
  1573. acmCol.setRowValue(aceRow, SYS_FULL_ACCESS_ACM);
  1574. inheritCol.setRowValue(aceRow, Boolean.FALSE);
  1575. objIdCol.setRowValue(aceRow, objectId);
  1576. sidCol.setRowValue(aceRow, sid);
  1577. aceRows.add(aceRow);
  1578. }
  1579. acEntries.addRows(aceRows);
  1580. }
  1581. /**
  1582. * Find collection of SIDs for the given parent id.
  1583. */
  1584. private void collectNewObjectSIDs(Integer parentId, List<byte[]> sids)
  1585. throws IOException
  1586. {
  1587. // search for ACEs matching the given parentId. use the index on the
  1588. // objectId column if found (should be there)
  1589. Cursor cursor = createCursorWithOptionalIndex(
  1590. getAccessControlEntries(), ACE_COL_OBJECT_ID, parentId);
  1591. for(Row row : cursor) {
  1592. Integer objId = row.getInt(ACE_COL_OBJECT_ID);
  1593. if(parentId.equals(objId)) {
  1594. sids.add(row.getBytes(ACE_COL_SID));
  1595. }
  1596. }
  1597. if(sids.isEmpty()) {
  1598. // if all else fails, use the hard-coded default
  1599. sids.add(SYS_DEFAULT_SID);
  1600. }
  1601. }
  1602. /**
  1603. * Reads a table with the given name from the given pageNumber.
  1604. */
  1605. private TableImpl readTable(String name, int pageNumber, int flags)
  1606. throws IOException
  1607. {
  1608. // first, check for existing table
  1609. TableImpl table = _tableCache.get(pageNumber);
  1610. if(table != null) {
  1611. return table;
  1612. }
  1613. ByteBuffer buffer = takeSharedBuffer();
  1614. try {
  1615. // need to load table from db
  1616. _pageChannel.readPage(buffer, pageNumber);
  1617. byte pageType = buffer.get(0);
  1618. if (pageType != PageTypes.TABLE_DEF) {
  1619. throw new IOException(withErrorContext(
  1620. "Looking for " + name + " at page " + pageNumber +
  1621. ", but page type is " + pageType));
  1622. }
  1623. return _tableCache.put(
  1624. new TableImpl(this, buffer, pageNumber, name, flags));
  1625. } finally {
  1626. releaseSharedBuffer(buffer);
  1627. }
  1628. }
  1629. /**
  1630. * Creates a Cursor restricted to the given column value if possible (using
  1631. * an existing index), otherwise a simple table cursor.
  1632. */
  1633. private Cursor createCursorWithOptionalIndex(
  1634. TableImpl table, String colName, Object colValue)
  1635. throws IOException
  1636. {
  1637. try {
  1638. return table.newCursor()
  1639. .setIndexByColumnNames(colName)
  1640. .setSpecificEntry(colValue)
  1641. .toCursor();
  1642. } catch(IllegalArgumentException e) {
  1643. if(LOG.isDebugEnabled()) {
  1644. LOG.debug(withErrorContext(
  1645. "Could not find expected index on table " + table.getName()));
  1646. }
  1647. }
  1648. // use table scan instead
  1649. return CursorImpl.createCursor(table);
  1650. }
  1651. @Override
  1652. public void flush() throws IOException {
  1653. if(_linkedDbs != null) {
  1654. for(Database linkedDb : _linkedDbs.values()) {
  1655. linkedDb.flush();
  1656. }
  1657. }
  1658. _pageChannel.flush();
  1659. }
  1660. @Override
  1661. public void close() throws IOException {
  1662. if(_linkedDbs != null) {
  1663. for(Database linkedDb : _linkedDbs.values()) {
  1664. linkedDb.close();
  1665. }
  1666. }
  1667. _pageChannel.close();
  1668. }
  1669. public void validateNewTableName(String name) throws IOException {
  1670. validateIdentifierName(name, getFormat().MAX_TABLE_NAME_LENGTH, "table");
  1671. if(lookupTable(name) != null) {
  1672. throw new IllegalArgumentException(withErrorContext(
  1673. "Cannot create table with name of existing table '" + name + "'"));
  1674. }
  1675. }
  1676. /**
  1677. * Validates an identifier name.
  1678. *
  1679. * Names of fields, controls, and objects in Microsoft Access:
  1680. * <ul>
  1681. * <li>Can include any combination of letters, numbers, spaces, and special
  1682. * characters except a period (.), an exclamation point (!), an accent
  1683. * grave (`), and brackets ([ ]).</li>
  1684. * <li>Can't begin with leading spaces.</li>
  1685. * <li>Can't include control characters (ASCII values 0 through 31).</li>
  1686. * </ul>
  1687. *
  1688. * @usage _advanced_method_
  1689. */
  1690. public static void validateIdentifierName(String name,
  1691. int maxLength,
  1692. String identifierType)
  1693. {
  1694. // basic name validation
  1695. validateName(name, maxLength, identifierType);
  1696. // additional identifier validation
  1697. if(INVALID_IDENTIFIER_CHARS.matcher(name).find()) {
  1698. throw new IllegalArgumentException(
  1699. identifierType + " name '" + name + "' contains invalid characters");
  1700. }
  1701. // cannot start with spaces
  1702. if(name.charAt(0) == ' ') {
  1703. throw new IllegalArgumentException(
  1704. identifierType + " name '" + name +
  1705. "' cannot start with a space character");
  1706. }
  1707. }
  1708. /**
  1709. * Validates a name.
  1710. */
  1711. private static void validateName(String name, int maxLength, String nameType)
  1712. {
  1713. if(isBlank(name)) {
  1714. throw new IllegalArgumentException(
  1715. nameType + " must have non-blank name");
  1716. }
  1717. if(name.length() > maxLength) {
  1718. throw new IllegalArgumentException(
  1719. nameType + " name is longer than max length of " + maxLength +
  1720. ": " + name);
  1721. }
  1722. }
  1723. /**
  1724. * Returns {@code true} if the given string is {@code null} or all blank
  1725. * space, {@code false} otherwise.
  1726. */
  1727. public static boolean isBlank(String name) {
  1728. return StringUtils.isBlank(name);
  1729. }
  1730. /**
  1731. * Returns the given string trimmed, or {@code null} if the string is {@code
  1732. * null} or empty.
  1733. */
  1734. public static String trimToNull(String str) {
  1735. return StringUtils.trimToNull(str);
  1736. }
  1737. @Override
  1738. public String toString() {
  1739. return ToStringBuilder.reflectionToString(this);
  1740. }
  1741. /**
  1742. * Adds a table to the _tableLookup and resets the _tableNames set
  1743. */
  1744. private void addTable(String tableName, Integer pageNumber, Short type,
  1745. String linkedDbName, String linkedTableName)
  1746. {
  1747. _tableLookup.put(toLookupName(tableName),
  1748. createTableInfo(tableName, pageNumber, 0, type,
  1749. linkedDbName, linkedTableName));
  1750. // clear this, will be created next time needed
  1751. _tableNames = null;
  1752. }
  1753. /**
  1754. * Creates a TableInfo instance appropriate for the given table data.
  1755. */
  1756. private static TableInfo createTableInfo(
  1757. String tableName, Integer pageNumber, int flags, Short type,
  1758. String linkedDbName, String linkedTableName)
  1759. {
  1760. if(TYPE_LINKED_TABLE.equals(type)) {
  1761. return new LinkedTableInfo(pageNumber, tableName, flags, linkedDbName,
  1762. linkedTableName);
  1763. }
  1764. return new TableInfo(pageNumber, tableName, flags);
  1765. }
  1766. /**
  1767. * @return the tableInfo of the given table, if any
  1768. */
  1769. private TableInfo lookupTable(String tableName) throws IOException {
  1770. String lookupTableName = toLookupName(tableName);
  1771. TableInfo tableInfo = _tableLookup.get(lookupTableName);
  1772. if(tableInfo != null) {
  1773. return tableInfo;
  1774. }
  1775. tableInfo = _tableFinder.lookupTable(tableName);
  1776. if(tableInfo != null) {
  1777. // cache for later
  1778. _tableLookup.put(lookupTableName, tableInfo);
  1779. }
  1780. return tableInfo;
  1781. }
  1782. /**
  1783. * @return a string usable in the _tableLookup map.
  1784. */
  1785. public static String toLookupName(String name) {
  1786. return ((name != null) ? name.toUpperCase() : null);
  1787. }
  1788. /**
  1789. * @return {@code true} if the given flags indicate that an object is some
  1790. * sort of system object, {@code false} otherwise.
  1791. */
  1792. private static boolean isSystemObject(int flags) {
  1793. return ((flags & SYSTEM_OBJECT_FLAGS) != 0);
  1794. }
  1795. /**
  1796. * Returns the default TimeZone. This is normally the platform default
  1797. * TimeZone as returned by {@link TimeZone#getDefault}, but can be
  1798. * overridden using the system property
  1799. * {@value com.healthmarketscience.jackcess.Database#TIMEZONE_PROPERTY}.
  1800. * @usage _advanced_method_
  1801. */
  1802. public static TimeZone getDefaultTimeZone()
  1803. {
  1804. String tzProp = System.getProperty(TIMEZONE_PROPERTY);
  1805. if(tzProp != null) {
  1806. tzProp = tzProp.trim();
  1807. if(tzProp.length() > 0) {
  1808. return TimeZone.getTimeZone(tzProp);
  1809. }
  1810. }
  1811. // use system default
  1812. return TimeZone.getDefault();
  1813. }
  1814. /**
  1815. * Returns the default Charset for the given JetFormat. This may or may not
  1816. * be platform specific, depending on the format, but can be overridden
  1817. * using a system property composed of the prefix
  1818. * {@value com.healthmarketscience.jackcess.Database#CHARSET_PROPERTY_PREFIX}
  1819. * followed by the JetFormat version to which the charset should apply,
  1820. * e.g. {@code "com.healthmarketscience.jackcess.charset.VERSION_3"}.
  1821. * @usage _advanced_method_
  1822. */
  1823. public static Charset getDefaultCharset(JetFormat format)
  1824. {
  1825. String csProp = System.getProperty(CHARSET_PROPERTY_PREFIX + format);
  1826. if(csProp != null) {
  1827. csProp = csProp.trim();
  1828. if(csProp.length() > 0) {
  1829. return Charset.forName(csProp);
  1830. }
  1831. }
  1832. // use format default
  1833. return format.CHARSET;
  1834. }
  1835. /**
  1836. * Returns the default Table.ColumnOrder. This defaults to
  1837. * {@link Database#DEFAULT_COLUMN_ORDER}, but can be overridden using the system
  1838. * property {@value com.healthmarketscience.jackcess.Database#COLUMN_ORDER_PROPERTY}.
  1839. * @usage _advanced_method_
  1840. */
  1841. public static Table.ColumnOrder getDefaultColumnOrder()
  1842. {
  1843. return getEnumSystemProperty(Table.ColumnOrder.class, COLUMN_ORDER_PROPERTY,
  1844. DEFAULT_COLUMN_ORDER);
  1845. }
  1846. /**
  1847. * Returns the default enforce foreign-keys policy. This defaults to
  1848. * {@code true}, but can be overridden using the system
  1849. * property {@value com.healthmarketscience.jackcess.Database#FK_ENFORCE_PROPERTY}.
  1850. * @usage _advanced_method_
  1851. */
  1852. public static boolean getDefaultEnforceForeignKeys()
  1853. {
  1854. String prop = System.getProperty(FK_ENFORCE_PROPERTY);
  1855. if(prop != null) {
  1856. return Boolean.TRUE.toString().equalsIgnoreCase(prop);
  1857. }
  1858. return true;
  1859. }
  1860. /**
  1861. * Returns the default allow auto number insert policy. This defaults to
  1862. * {@code false}, but can be overridden using the system
  1863. * property {@value com.healthmarketscience.jackcess.Database#ALLOW_AUTONUM_INSERT_PROPERTY}.
  1864. * @usage _advanced_method_
  1865. */
  1866. public static boolean getDefaultAllowAutoNumberInsert()
  1867. {
  1868. String prop = System.getProperty(ALLOW_AUTONUM_INSERT_PROPERTY);
  1869. if(prop != null) {
  1870. return Boolean.TRUE.toString().equalsIgnoreCase(prop);
  1871. }
  1872. return false;
  1873. }
  1874. /**
  1875. * Returns the default enable expression evaluation policy. This defaults to
  1876. * {@code true}, but can be overridden using the system
  1877. * property {@value com.healthmarketscience.jackcess.Database#ENABLE_EXPRESSION_EVALUATION_PROPERTY}.
  1878. * @usage _advanced_method_
  1879. */
  1880. public static boolean getDefaultEvaluateExpressions()
  1881. {
  1882. String prop = System.getProperty(ENABLE_EXPRESSION_EVALUATION_PROPERTY);
  1883. if(prop != null) {
  1884. return Boolean.TRUE.toString().equalsIgnoreCase(prop);
  1885. }
  1886. return true;
  1887. }
  1888. /**
  1889. * Returns the default DateTimeType. This defaults to
  1890. * {@link DateTimeType#LOCAL_DATE_TIME}, but can be overridden using the system
  1891. * property {@value com.healthmarketscience.jackcess.Database#DATE_TIME_TYPE_PROPERTY}.
  1892. * @usage _advanced_method_
  1893. */
  1894. public static DateTimeType getDefaultDateTimeType() {
  1895. return getEnumSystemProperty(DateTimeType.class, DATE_TIME_TYPE_PROPERTY,
  1896. DateTimeType.LOCAL_DATE_TIME);
  1897. }
  1898. /**
  1899. * Copies the given db InputStream to the given channel using the most
  1900. * efficient means possible.
  1901. */
  1902. protected static void transferDbFrom(FileChannel channel, InputStream in)
  1903. throws IOException
  1904. {
  1905. ReadableByteChannel readChannel = Channels.newChannel(in);
  1906. if(!BROKEN_NIO) {
  1907. // sane implementation
  1908. channel.transferFrom(readChannel, 0, MAX_EMPTYDB_SIZE);
  1909. } else {
  1910. // do things the hard way for broken vms
  1911. ByteBuffer bb = ByteBuffer.allocate(8096);
  1912. while(readChannel.read(bb) >= 0) {
  1913. bb.flip();
  1914. channel.write(bb);
  1915. bb.clear();
  1916. }
  1917. }
  1918. }
  1919. /**
  1920. * Returns the password mask retrieved from the given header page and
  1921. * format, or {@code null} if this format does not use a password mask.
  1922. * @usage _advanced_method_
  1923. */
  1924. public static byte[] getPasswordMask(ByteBuffer buffer, JetFormat format)
  1925. {
  1926. // get extra password mask if necessary (the extra password mask is
  1927. // generated from the database creation date stored in the header)
  1928. int pwdMaskPos = format.OFFSET_HEADER_DATE;
  1929. if(pwdMaskPos < 0) {
  1930. return null;
  1931. }
  1932. buffer.position(pwdMaskPos);
  1933. double dateVal = Double.longBitsToDouble(buffer.getLong());
  1934. byte[] pwdMask = new byte[4];
  1935. PageChannel.wrap(pwdMask).putInt((int)dateVal);
  1936. return pwdMask;
  1937. }
  1938. protected static InputStream getResourceAsStream(String resourceName)
  1939. throws IOException
  1940. {
  1941. InputStream stream = DatabaseImpl.class.getClassLoader()
  1942. .getResourceAsStream(resourceName);
  1943. if(stream == null) {
  1944. stream = Thread.currentThread().getContextClassLoader()
  1945. .getResourceAsStream(resourceName);
  1946. if(stream == null) {
  1947. throw new IOException("Could not load jackcess resource " +
  1948. resourceName);
  1949. }
  1950. }
  1951. return stream;
  1952. }
  1953. private static boolean isTableType(Short objType) {
  1954. return(TYPE_TABLE.equals(objType) || TYPE_LINKED_TABLE.equals(objType));
  1955. }
  1956. public static FileFormatDetails getFileFormatDetails(FileFormat fileFormat) {
  1957. return FILE_FORMAT_DETAILS.get(fileFormat);
  1958. }
  1959. private static void addFileFormatDetails(
  1960. FileFormat fileFormat, String emptyFileName, JetFormat format)
  1961. {
  1962. String emptyFile =
  1963. ((emptyFileName != null) ?
  1964. RESOURCE_PATH + emptyFileName + fileFormat.getFileExtension() : null);
  1965. FILE_FORMAT_DETAILS.put(fileFormat, new FileFormatDetails(emptyFile, format));
  1966. }
  1967. private static String getName(Path file) {
  1968. if(file == null) {
  1969. return "<UNKNOWN.DB>";
  1970. }
  1971. return file.getFileName().toString();
  1972. }
  1973. private String withErrorContext(String msg) {
  1974. return withErrorContext(msg, getName());
  1975. }
  1976. private static String withErrorContext(String msg, String dbName) {
  1977. return msg + " (Db=" + dbName + ")";
  1978. }
  1979. private static <E extends Enum<E>> E getEnumSystemProperty(
  1980. Class<E> enumClass, String propName, E defaultValue)
  1981. {
  1982. String prop = System.getProperty(propName);
  1983. if(prop != null) {
  1984. prop = prop.trim().toUpperCase();
  1985. if(!prop.isEmpty()) {
  1986. return Enum.valueOf(enumClass, prop);
  1987. }
  1988. }
  1989. return defaultValue;
  1990. }
  1991. /**
  1992. * Utility class for storing table page number and actual name.
  1993. */
  1994. private static class TableInfo implements TableMetaData
  1995. {
  1996. public final Integer pageNumber;
  1997. public final String tableName;
  1998. public final int flags;
  1999. private TableInfo(Integer newPageNumber, String newTableName, int newFlags) {
  2000. pageNumber = newPageNumber;
  2001. tableName = newTableName;
  2002. flags = newFlags;
  2003. }
  2004. @Override
  2005. public String getName() {
  2006. return tableName;
  2007. }
  2008. @Override
  2009. public boolean isLinked() {
  2010. return false;
  2011. }
  2012. @Override
  2013. public boolean isSystem() {
  2014. return isSystemObject(flags);
  2015. }
  2016. @Override
  2017. public String getLinkedTableName() {
  2018. return null;
  2019. }
  2020. @Override
  2021. public String getLinkedDbName() {
  2022. return null;
  2023. }
  2024. @Override
  2025. public Table open(Database db) throws IOException {
  2026. return ((DatabaseImpl)db).getTable(this, true);
  2027. }
  2028. @Override
  2029. public String toString() {
  2030. ToStringBuilder sb = CustomToStringStyle.valueBuilder("TableMetaData")
  2031. .append("name", getName());
  2032. if(isSystem()) {
  2033. sb.append("isSystem", isSystem());
  2034. }
  2035. if(isLinked()) {
  2036. sb.append("isLinked", isLinked())
  2037. .append("linkedTableName", getLinkedTableName())
  2038. .append("linkedDbName", getLinkedDbName());
  2039. }
  2040. return sb.toString();
  2041. }
  2042. }
  2043. /**
  2044. * Utility class for storing linked table info
  2045. */
  2046. private static class LinkedTableInfo extends TableInfo
  2047. {
  2048. private final String linkedDbName;
  2049. private final String linkedTableName;
  2050. private LinkedTableInfo(Integer newPageNumber, String newTableName,
  2051. int newFlags, String newLinkedDbName,
  2052. String newLinkedTableName) {
  2053. super(newPageNumber, newTableName, newFlags);
  2054. linkedDbName = newLinkedDbName;
  2055. linkedTableName = newLinkedTableName;
  2056. }
  2057. @Override
  2058. public boolean isLinked() {
  2059. return true;
  2060. }
  2061. @Override
  2062. public String getLinkedTableName() {
  2063. return linkedTableName;
  2064. }
  2065. @Override
  2066. public String getLinkedDbName() {
  2067. return linkedDbName;
  2068. }
  2069. }
  2070. /**
  2071. * Table iterator for this database, unmodifiable.
  2072. */
  2073. private class TableIterator implements Iterator<Table>
  2074. {
  2075. private Iterator<String> _tableNameIter;
  2076. private TableIterator(Set<String> tableNames) {
  2077. _tableNameIter = tableNames.iterator();
  2078. }
  2079. @Override
  2080. public boolean hasNext() {
  2081. return _tableNameIter.hasNext();
  2082. }
  2083. @Override
  2084. public Table next() {
  2085. if(!hasNext()) {
  2086. throw new NoSuchElementException();
  2087. }
  2088. try {
  2089. return getTable(_tableNameIter.next(), true);
  2090. } catch(IOException e) {
  2091. throw new RuntimeIOException(e);
  2092. }
  2093. }
  2094. }
  2095. /**
  2096. * Utility class for handling table lookups.
  2097. */
  2098. private abstract class TableFinder
  2099. {
  2100. public Integer findObjectId(Integer parentId, String name)
  2101. throws IOException
  2102. {
  2103. Cursor cur = findRow(parentId, name);
  2104. if(cur == null) {
  2105. return null;
  2106. }
  2107. ColumnImpl idCol = _systemCatalog.getColumn(CAT_COL_ID);
  2108. return (Integer)cur.getCurrentRowValue(idCol);
  2109. }
  2110. public Row getObjectRow(Integer parentId, String name,
  2111. Collection<String> columns)
  2112. throws IOException
  2113. {
  2114. Cursor cur = findRow(parentId, name);
  2115. return ((cur != null) ? cur.getCurrentRow(columns) : null);
  2116. }
  2117. public Row getObjectRow(
  2118. Integer objectId, Collection<String> columns)
  2119. throws IOException
  2120. {
  2121. Cursor cur = findRow(objectId);
  2122. return ((cur != null) ? cur.getCurrentRow(columns) : null);
  2123. }
  2124. public void getTableNames(Set<String> tableNames,
  2125. boolean normalTables,
  2126. boolean systemTables,
  2127. boolean linkedTables)
  2128. throws IOException
  2129. {
  2130. for(Row row : getTableNamesCursor().newIterable().setColumnNames(
  2131. SYSTEM_CATALOG_COLUMNS)) {
  2132. String tableName = row.getString(CAT_COL_NAME);
  2133. int flags = row.getInt(CAT_COL_FLAGS);
  2134. Short type = row.getShort(CAT_COL_TYPE);
  2135. int parentId = row.getInt(CAT_COL_PARENT_ID);
  2136. if(parentId != _tableParentId) {
  2137. continue;
  2138. }
  2139. if(TYPE_TABLE.equals(type)) {
  2140. if(!isSystemObject(flags)) {
  2141. if(normalTables) {
  2142. tableNames.add(tableName);
  2143. }
  2144. } else if(systemTables) {
  2145. tableNames.add(tableName);
  2146. }
  2147. } else if(TYPE_LINKED_TABLE.equals(type) && linkedTables) {
  2148. tableNames.add(tableName);
  2149. }
  2150. }
  2151. }
  2152. public boolean isLinkedTable(Table table) throws IOException
  2153. {
  2154. for(Row row : getTableNamesCursor().newIterable().setColumnNames(
  2155. SYSTEM_CATALOG_TABLE_DETAIL_COLUMNS)) {
  2156. Short type = row.getShort(CAT_COL_TYPE);
  2157. String linkedDbName = row.getString(CAT_COL_DATABASE);
  2158. String linkedTableName = row.getString(CAT_COL_FOREIGN_NAME);
  2159. if(TYPE_LINKED_TABLE.equals(type) &&
  2160. matchesLinkedTable(table, linkedTableName, linkedDbName)) {
  2161. return true;
  2162. }
  2163. }
  2164. return false;
  2165. }
  2166. public int getNextFreeSyntheticId() throws IOException {
  2167. int maxSynthId = findMaxSyntheticId();
  2168. if(maxSynthId >= -1) {
  2169. // bummer, no more ids available
  2170. throw new IllegalStateException(withErrorContext(
  2171. "Too many database objects!"));
  2172. }
  2173. return maxSynthId + 1;
  2174. }
  2175. public Iterator<TableMetaData> iterateTableMetaData() throws IOException {
  2176. return new Iterator<TableMetaData>() {
  2177. private final Iterator<Row> _iter =
  2178. getTableNamesCursor().newIterable().setColumnNames(
  2179. SYSTEM_CATALOG_TABLE_DETAIL_COLUMNS).iterator();
  2180. private TableMetaData _next;
  2181. @Override
  2182. public boolean hasNext() {
  2183. if((_next == null) && _iter.hasNext()) {
  2184. _next = nextTableMetaData(_iter);
  2185. }
  2186. return (_next != null);
  2187. }
  2188. @Override
  2189. public TableMetaData next() {
  2190. if(!hasNext()) {
  2191. throw new NoSuchElementException();
  2192. }
  2193. TableMetaData next = _next;
  2194. _next = null;
  2195. return next;
  2196. }
  2197. };
  2198. }
  2199. private TableMetaData nextTableMetaData(Iterator<Row> detailIter) {
  2200. while(detailIter.hasNext()) {
  2201. Row row = detailIter.next();
  2202. Short type = row.getShort(CAT_COL_TYPE);
  2203. if(!isTableType(type)) {
  2204. continue;
  2205. }
  2206. int parentId = row.getInt(CAT_COL_PARENT_ID);
  2207. if(parentId != _tableParentId) {
  2208. continue;
  2209. }
  2210. String realName = row.getString(CAT_COL_NAME);
  2211. Integer pageNumber = row.getInt(CAT_COL_ID);
  2212. int flags = row.getInt(CAT_COL_FLAGS);
  2213. String linkedDbName = row.getString(CAT_COL_DATABASE);
  2214. String linkedTableName = row.getString(CAT_COL_FOREIGN_NAME);
  2215. return createTableInfo(realName, pageNumber, flags, type, linkedDbName,
  2216. linkedTableName);
  2217. }
  2218. return null;
  2219. }
  2220. protected abstract Cursor findRow(Integer parentId, String name)
  2221. throws IOException;
  2222. protected abstract Cursor findRow(Integer objectId)
  2223. throws IOException;
  2224. protected abstract Cursor getTableNamesCursor() throws IOException;
  2225. public abstract TableInfo lookupTable(String tableName)
  2226. throws IOException;
  2227. protected abstract int findMaxSyntheticId() throws IOException;
  2228. }
  2229. /**
  2230. * Normal table lookup handler, using catalog table index.
  2231. */
  2232. private final class DefaultTableFinder extends TableFinder
  2233. {
  2234. private final IndexCursor _systemCatalogCursor;
  2235. private IndexCursor _systemCatalogIdCursor;
  2236. private DefaultTableFinder(IndexCursor systemCatalogCursor) {
  2237. _systemCatalogCursor = systemCatalogCursor;
  2238. }
  2239. private void initIdCursor() throws IOException {
  2240. if(_systemCatalogIdCursor == null) {
  2241. _systemCatalogIdCursor = _systemCatalog.newCursor()
  2242. .setIndexByColumnNames(CAT_COL_ID)
  2243. .toIndexCursor();
  2244. }
  2245. }
  2246. @Override
  2247. protected Cursor findRow(Integer parentId, String name)
  2248. throws IOException
  2249. {
  2250. return (_systemCatalogCursor.findFirstRowByEntry(parentId, name) ?
  2251. _systemCatalogCursor : null);
  2252. }
  2253. @Override
  2254. protected Cursor findRow(Integer objectId) throws IOException
  2255. {
  2256. initIdCursor();
  2257. return (_systemCatalogIdCursor.findFirstRowByEntry(objectId) ?
  2258. _systemCatalogIdCursor : null);
  2259. }
  2260. @Override
  2261. public TableInfo lookupTable(String tableName) throws IOException {
  2262. if(findRow(_tableParentId, tableName) == null) {
  2263. return null;
  2264. }
  2265. Row row = _systemCatalogCursor.getCurrentRow(
  2266. SYSTEM_CATALOG_TABLE_DETAIL_COLUMNS);
  2267. Integer pageNumber = row.getInt(CAT_COL_ID);
  2268. String realName = row.getString(CAT_COL_NAME);
  2269. int flags = row.getInt(CAT_COL_FLAGS);
  2270. Short type = row.getShort(CAT_COL_TYPE);
  2271. if(!isTableType(type)) {
  2272. return null;
  2273. }
  2274. String linkedDbName = row.getString(CAT_COL_DATABASE);
  2275. String linkedTableName = row.getString(CAT_COL_FOREIGN_NAME);
  2276. return createTableInfo(realName, pageNumber, flags, type, linkedDbName,
  2277. linkedTableName);
  2278. }
  2279. @Override
  2280. protected Cursor getTableNamesCursor() throws IOException {
  2281. return _systemCatalogCursor.getIndex().newCursor()
  2282. .setStartEntry(_tableParentId, IndexData.MIN_VALUE)
  2283. .setEndEntry(_tableParentId, IndexData.MAX_VALUE)
  2284. .toIndexCursor();
  2285. }
  2286. @Override
  2287. protected int findMaxSyntheticId() throws IOException {
  2288. initIdCursor();
  2289. _systemCatalogIdCursor.reset();
  2290. // synthetic ids count up from min integer. so the current, highest,
  2291. // in-use synthetic id is the max id < 0.
  2292. _systemCatalogIdCursor.findClosestRowByEntry(0);
  2293. if(!_systemCatalogIdCursor.moveToPreviousRow()) {
  2294. return Integer.MIN_VALUE;
  2295. }
  2296. ColumnImpl idCol = _systemCatalog.getColumn(CAT_COL_ID);
  2297. return (Integer)_systemCatalogIdCursor.getCurrentRowValue(idCol);
  2298. }
  2299. }
  2300. /**
  2301. * Fallback table lookup handler, using catalog table scans.
  2302. */
  2303. private final class FallbackTableFinder extends TableFinder
  2304. {
  2305. private final Cursor _systemCatalogCursor;
  2306. private FallbackTableFinder(Cursor systemCatalogCursor) {
  2307. _systemCatalogCursor = systemCatalogCursor;
  2308. }
  2309. @Override
  2310. protected Cursor findRow(Integer parentId, String name)
  2311. throws IOException
  2312. {
  2313. Map<String,Object> rowPat = new HashMap<String,Object>();
  2314. rowPat.put(CAT_COL_PARENT_ID, parentId);
  2315. rowPat.put(CAT_COL_NAME, name);
  2316. return (_systemCatalogCursor.findFirstRow(rowPat) ?
  2317. _systemCatalogCursor : null);
  2318. }
  2319. @Override
  2320. protected Cursor findRow(Integer objectId) throws IOException
  2321. {
  2322. ColumnImpl idCol = _systemCatalog.getColumn(CAT_COL_ID);
  2323. return (_systemCatalogCursor.findFirstRow(idCol, objectId) ?
  2324. _systemCatalogCursor : null);
  2325. }
  2326. @Override
  2327. public TableInfo lookupTable(String tableName) throws IOException {
  2328. for(Row row : _systemCatalogCursor.newIterable().setColumnNames(
  2329. SYSTEM_CATALOG_TABLE_DETAIL_COLUMNS)) {
  2330. Short type = row.getShort(CAT_COL_TYPE);
  2331. if(!isTableType(type)) {
  2332. continue;
  2333. }
  2334. int parentId = row.getInt(CAT_COL_PARENT_ID);
  2335. if(parentId != _tableParentId) {
  2336. continue;
  2337. }
  2338. String realName = row.getString(CAT_COL_NAME);
  2339. if(!tableName.equalsIgnoreCase(realName)) {
  2340. continue;
  2341. }
  2342. Integer pageNumber = row.getInt(CAT_COL_ID);
  2343. int flags = row.getInt(CAT_COL_FLAGS);
  2344. String linkedDbName = row.getString(CAT_COL_DATABASE);
  2345. String linkedTableName = row.getString(CAT_COL_FOREIGN_NAME);
  2346. return createTableInfo(realName, pageNumber, flags, type, linkedDbName,
  2347. linkedTableName);
  2348. }
  2349. return null;
  2350. }
  2351. @Override
  2352. protected Cursor getTableNamesCursor() throws IOException {
  2353. return _systemCatalogCursor;
  2354. }
  2355. @Override
  2356. protected int findMaxSyntheticId() throws IOException {
  2357. // find max id < 0
  2358. ColumnImpl idCol = _systemCatalog.getColumn(CAT_COL_ID);
  2359. _systemCatalogCursor.reset();
  2360. int curMaxSynthId = Integer.MIN_VALUE;
  2361. while(_systemCatalogCursor.moveToNextRow()) {
  2362. int id = (Integer)_systemCatalogCursor.getCurrentRowValue(idCol);
  2363. if((id > curMaxSynthId) && (id < 0)) {
  2364. curMaxSynthId = id;
  2365. }
  2366. }
  2367. return curMaxSynthId;
  2368. }
  2369. }
  2370. /**
  2371. * WeakReference for a Table which holds the table pageNumber (for later
  2372. * cache purging).
  2373. */
  2374. private static final class WeakTableReference extends WeakReference<TableImpl>
  2375. {
  2376. private final Integer _pageNumber;
  2377. private WeakTableReference(Integer pageNumber, TableImpl table,
  2378. ReferenceQueue<TableImpl> queue) {
  2379. super(table, queue);
  2380. _pageNumber = pageNumber;
  2381. }
  2382. public Integer getPageNumber() {
  2383. return _pageNumber;
  2384. }
  2385. }
  2386. /**
  2387. * Cache of currently in-use tables, allows re-use of existing tables.
  2388. */
  2389. private static final class TableCache
  2390. {
  2391. private final Map<Integer,WeakTableReference> _tables =
  2392. new HashMap<Integer,WeakTableReference>();
  2393. private final ReferenceQueue<TableImpl> _queue =
  2394. new ReferenceQueue<TableImpl>();
  2395. public TableImpl get(Integer pageNumber) {
  2396. WeakTableReference ref = _tables.get(pageNumber);
  2397. return ((ref != null) ? ref.get() : null);
  2398. }
  2399. public TableImpl put(TableImpl table) {
  2400. purgeOldRefs();
  2401. Integer pageNumber = table.getTableDefPageNumber();
  2402. WeakTableReference ref = new WeakTableReference(
  2403. pageNumber, table, _queue);
  2404. _tables.put(pageNumber, ref);
  2405. return table;
  2406. }
  2407. private void purgeOldRefs() {
  2408. WeakTableReference oldRef = null;
  2409. while((oldRef = (WeakTableReference)_queue.poll()) != null) {
  2410. _tables.remove(oldRef.getPageNumber());
  2411. }
  2412. }
  2413. }
  2414. /**
  2415. * Internal details for each FileForrmat
  2416. * @usage _advanced_class_
  2417. */
  2418. public static final class FileFormatDetails
  2419. {
  2420. private final String _emptyFile;
  2421. private final JetFormat _format;
  2422. private FileFormatDetails(String emptyFile, JetFormat format) {
  2423. _emptyFile = emptyFile;
  2424. _format = format;
  2425. }
  2426. public String getEmptyFilePath() {
  2427. return _emptyFile;
  2428. }
  2429. public JetFormat getFormat() {
  2430. return _format;
  2431. }
  2432. }
  2433. }