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

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