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

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