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

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