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

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