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

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