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.

Database.java 86KB

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