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

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