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 76KB

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