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

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