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

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