You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

DatabaseImpl.java 85KB

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