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

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