Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

IndexImpl.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  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.IOException;
  15. import java.nio.ByteBuffer;
  16. import java.util.Collections;
  17. import java.util.List;
  18. import java.util.Map;
  19. import com.healthmarketscience.jackcess.CursorBuilder;
  20. import com.healthmarketscience.jackcess.Index;
  21. import com.healthmarketscience.jackcess.IndexBuilder;
  22. import org.apache.commons.lang.builder.ToStringBuilder;
  23. import org.apache.commons.logging.Log;
  24. import org.apache.commons.logging.LogFactory;
  25. /**
  26. * Access table (logical) index. Logical indexes are backed for IndexData,
  27. * where one or more logical indexes could be backed by the same data.
  28. *
  29. * @author Tim McCune
  30. */
  31. public class IndexImpl implements Index, Comparable<IndexImpl>
  32. {
  33. protected static final Log LOG = LogFactory.getLog(IndexImpl.class);
  34. /** index type for primary key indexes */
  35. public static final byte PRIMARY_KEY_INDEX_TYPE = (byte)1;
  36. /** index type for foreign key indexes */
  37. public static final byte FOREIGN_KEY_INDEX_TYPE = (byte)2;
  38. /** flag for indicating that updates should cascade in a foreign key index */
  39. private static final byte CASCADE_UPDATES_FLAG = (byte)1;
  40. /** flag for indicating that deletes should cascade in a foreign key index */
  41. private static final byte CASCADE_DELETES_FLAG = (byte)1;
  42. /** flag for indicating that deletes should cascade a null in a foreign key
  43. index */
  44. private static final byte CASCADE_NULL_FLAG = (byte)2;
  45. /** index table type for the "primary" table in a foreign key index */
  46. static final byte PRIMARY_TABLE_TYPE = (byte)1;
  47. /** index table type for the "secondary" table in a foreign key index */
  48. static final byte SECONDARY_TABLE_TYPE = (byte)2;
  49. /** indicate an invalid index number for foreign key field */
  50. private static final int INVALID_INDEX_NUMBER = -1;
  51. /** the actual data backing this index (more than one index may be backed by
  52. the same data */
  53. private final IndexData _data;
  54. /** 0-based index number */
  55. private final int _indexNumber;
  56. /** the type of the index */
  57. private final byte _indexType;
  58. /** Index name */
  59. private String _name;
  60. /** foreign key reference info, if any */
  61. private final ForeignKeyReference _reference;
  62. protected IndexImpl(ByteBuffer tableBuffer, List<IndexData> indexDatas,
  63. JetFormat format)
  64. throws IOException
  65. {
  66. ByteUtil.forward(tableBuffer, format.SKIP_BEFORE_INDEX_SLOT); //Forward past Unknown
  67. _indexNumber = tableBuffer.getInt();
  68. int indexDataNumber = tableBuffer.getInt();
  69. // read foreign key reference info
  70. byte relIndexType = tableBuffer.get();
  71. int relIndexNumber = tableBuffer.getInt();
  72. int relTablePageNumber = tableBuffer.getInt();
  73. byte cascadeUpdatesFlag = tableBuffer.get();
  74. byte cascadeDeletesFlag = tableBuffer.get();
  75. _indexType = tableBuffer.get();
  76. if((_indexType == FOREIGN_KEY_INDEX_TYPE) &&
  77. (relIndexNumber != INVALID_INDEX_NUMBER)) {
  78. _reference = new ForeignKeyReference(
  79. relIndexType, relIndexNumber, relTablePageNumber,
  80. ((cascadeUpdatesFlag & CASCADE_UPDATES_FLAG) != 0),
  81. ((cascadeDeletesFlag & CASCADE_DELETES_FLAG) != 0),
  82. ((cascadeDeletesFlag & CASCADE_NULL_FLAG) != 0));
  83. } else {
  84. _reference = null;
  85. }
  86. ByteUtil.forward(tableBuffer, format.SKIP_AFTER_INDEX_SLOT); //Skip past Unknown
  87. _data = indexDatas.get(indexDataNumber);
  88. _data.addIndex(this);
  89. }
  90. public IndexData getIndexData() {
  91. return _data;
  92. }
  93. public TableImpl getTable() {
  94. return getIndexData().getTable();
  95. }
  96. public JetFormat getFormat() {
  97. return getTable().getFormat();
  98. }
  99. public PageChannel getPageChannel() {
  100. return getTable().getPageChannel();
  101. }
  102. public int getIndexNumber() {
  103. return _indexNumber;
  104. }
  105. public byte getIndexFlags() {
  106. return getIndexData().getIndexFlags();
  107. }
  108. public int getUniqueEntryCount() {
  109. return getIndexData().getUniqueEntryCount();
  110. }
  111. public int getUniqueEntryCountOffset() {
  112. return getIndexData().getUniqueEntryCountOffset();
  113. }
  114. public String getName() {
  115. return _name;
  116. }
  117. void setName(String name) {
  118. _name = name;
  119. }
  120. public boolean isPrimaryKey() {
  121. return _indexType == PRIMARY_KEY_INDEX_TYPE;
  122. }
  123. public boolean isForeignKey() {
  124. return _indexType == FOREIGN_KEY_INDEX_TYPE;
  125. }
  126. public ForeignKeyReference getReference() {
  127. return _reference;
  128. }
  129. public IndexImpl getReferencedIndex() throws IOException {
  130. if(_reference == null) {
  131. return null;
  132. }
  133. TableImpl refTable = getTable().getDatabase().getTable(
  134. _reference.getOtherTablePageNumber());
  135. if(refTable == null) {
  136. throw new IOException(withErrorContext(
  137. "Reference to missing table " + _reference.getOtherTablePageNumber()));
  138. }
  139. IndexImpl refIndex = null;
  140. int idxNumber = _reference.getOtherIndexNumber();
  141. for(IndexImpl idx : refTable.getIndexes()) {
  142. if(idx.getIndexNumber() == idxNumber) {
  143. refIndex = idx;
  144. break;
  145. }
  146. }
  147. if(refIndex == null) {
  148. throw new IOException(withErrorContext(
  149. "Reference to missing index " + idxNumber +
  150. " on table " + refTable.getName()));
  151. }
  152. // finally verify that we found the expected index (should reference this
  153. // index)
  154. ForeignKeyReference otherRef = refIndex.getReference();
  155. if((otherRef == null) ||
  156. (otherRef.getOtherTablePageNumber() !=
  157. getTable().getTableDefPageNumber()) ||
  158. (otherRef.getOtherIndexNumber() != _indexNumber)) {
  159. throw new IOException(withErrorContext(
  160. "Found unexpected index " + refIndex.getName() +
  161. " on table " + refTable.getName() + " with reference " + otherRef));
  162. }
  163. return refIndex;
  164. }
  165. public boolean shouldIgnoreNulls() {
  166. return getIndexData().shouldIgnoreNulls();
  167. }
  168. public boolean isUnique() {
  169. return getIndexData().isUnique();
  170. }
  171. public boolean isRequired() {
  172. return getIndexData().isRequired();
  173. }
  174. public List<IndexData.ColumnDescriptor> getColumns() {
  175. return getIndexData().getColumns();
  176. }
  177. public CursorBuilder newCursor() {
  178. return getTable().newCursor().setIndex(this);
  179. }
  180. /**
  181. * Whether or not the complete index state has been read.
  182. */
  183. public boolean isInitialized() {
  184. return getIndexData().isInitialized();
  185. }
  186. /**
  187. * Forces initialization of this index (actual parsing of index pages).
  188. * normally, the index will not be initialized until the entries are
  189. * actually needed.
  190. */
  191. public void initialize() throws IOException {
  192. getIndexData().initialize();
  193. }
  194. /**
  195. * Gets a new cursor for this index.
  196. * <p>
  197. * Forces index initialization.
  198. */
  199. public IndexData.EntryCursor cursor()
  200. throws IOException
  201. {
  202. return cursor(null, true, null, true);
  203. }
  204. /**
  205. * Gets a new cursor for this index, narrowed to the range defined by the
  206. * given startRow and endRow.
  207. * <p>
  208. * Forces index initialization.
  209. *
  210. * @param startRow the first row of data for the cursor, or {@code null} for
  211. * the first entry
  212. * @param startInclusive whether or not startRow is inclusive or exclusive
  213. * @param endRow the last row of data for the cursor, or {@code null} for
  214. * the last entry
  215. * @param endInclusive whether or not endRow is inclusive or exclusive
  216. */
  217. public IndexData.EntryCursor cursor(Object[] startRow,
  218. boolean startInclusive,
  219. Object[] endRow,
  220. boolean endInclusive)
  221. throws IOException
  222. {
  223. return getIndexData().cursor(startRow, startInclusive, endRow,
  224. endInclusive);
  225. }
  226. /**
  227. * Constructs an array of values appropriate for this index from the given
  228. * column values, expected to match the columns for this index.
  229. * @return the appropriate sparse array of data
  230. * @throws IllegalArgumentException if the wrong number of values are
  231. * provided
  232. */
  233. public Object[] constructIndexRowFromEntry(Object... values)
  234. {
  235. return getIndexData().constructIndexRowFromEntry(values);
  236. }
  237. /**
  238. * Constructs an array of values appropriate for this index from the given
  239. * column value.
  240. * @return the appropriate sparse array of data or {@code null} if not all
  241. * columns for this index were provided
  242. */
  243. public Object[] constructIndexRow(String colName, Object value)
  244. {
  245. return constructIndexRow(Collections.singletonMap(colName, value));
  246. }
  247. /**
  248. * Constructs an array of values appropriate for this index from the given
  249. * column values.
  250. * @return the appropriate sparse array of data or {@code null} if not all
  251. * columns for this index were provided
  252. */
  253. public Object[] constructIndexRow(Map<String,?> row)
  254. {
  255. return getIndexData().constructIndexRow(row);
  256. }
  257. @Override
  258. public String toString() {
  259. ToStringBuilder sb = CustomToStringStyle.builder(this)
  260. .append("name", "(" + getTable().getName() + ") " + _name)
  261. .append("number", _indexNumber)
  262. .append("isPrimaryKey", isPrimaryKey())
  263. .append("isForeignKey", isForeignKey());
  264. if(_reference != null) {
  265. sb.append("foreignKeyReference", _reference);
  266. }
  267. sb.append("data", _data);
  268. return sb.toString();
  269. }
  270. public int compareTo(IndexImpl other) {
  271. if (_indexNumber > other.getIndexNumber()) {
  272. return 1;
  273. } else if (_indexNumber < other.getIndexNumber()) {
  274. return -1;
  275. } else {
  276. return 0;
  277. }
  278. }
  279. /**
  280. * Writes the logical index definitions into a table definition buffer.
  281. * @param creator description of the indexes to write
  282. * @param buffer Buffer to write to
  283. */
  284. protected static void writeDefinitions(
  285. TableCreator creator, ByteBuffer buffer)
  286. throws IOException
  287. {
  288. // write logical index information
  289. for(IndexBuilder idx : creator.getIndexes()) {
  290. writeDefinition(creator, idx, buffer);
  291. }
  292. // write index names
  293. for(IndexBuilder idx : creator.getIndexes()) {
  294. TableImpl.writeName(buffer, idx.getName(), creator.getCharset());
  295. }
  296. }
  297. protected static void writeDefinition(
  298. TableMutator mutator, IndexBuilder idx, ByteBuffer buffer)
  299. throws IOException
  300. {
  301. TableMutator.IndexDataState idxDataState = mutator.getIndexDataState(idx);
  302. // write logical index information
  303. buffer.putInt(TableImpl.MAGIC_TABLE_NUMBER); // seemingly constant magic value which matches the table def
  304. buffer.putInt(idx.getIndexNumber()); // index num
  305. buffer.putInt(idxDataState.getIndexDataNumber()); // index data num
  306. byte idxType = idx.getType();
  307. if(idxType != FOREIGN_KEY_INDEX_TYPE) {
  308. buffer.put((byte)0); // related table type
  309. buffer.putInt(INVALID_INDEX_NUMBER); // related index num
  310. buffer.putInt(0); // related table definition page number
  311. buffer.put((byte)0); // cascade updates flag
  312. buffer.put((byte)0); // cascade deletes flag
  313. } else {
  314. ForeignKeyReference reference = mutator.getForeignKey(idx);
  315. buffer.put(reference.getTableType()); // related table type
  316. buffer.putInt(reference.getOtherIndexNumber()); // related index num
  317. buffer.putInt(reference.getOtherTablePageNumber()); // related table definition page number
  318. byte updateFlags = 0;
  319. if(reference.isCascadeUpdates()) {
  320. updateFlags |= CASCADE_UPDATES_FLAG;
  321. }
  322. byte deleteFlags = 0;
  323. if(reference.isCascadeDeletes()) {
  324. deleteFlags |= CASCADE_DELETES_FLAG;
  325. }
  326. if(reference.isCascadeNullOnDelete()) {
  327. deleteFlags |= CASCADE_NULL_FLAG;
  328. }
  329. buffer.put(updateFlags); // cascade updates flag
  330. buffer.put(deleteFlags); // cascade deletes flag
  331. }
  332. buffer.put(idxType); // index type flags
  333. buffer.putInt(0); // unknown
  334. }
  335. private String withErrorContext(String msg) {
  336. return withErrorContext(msg, getTable().getDatabase(), getName());
  337. }
  338. private static String withErrorContext(String msg, DatabaseImpl db,
  339. String idxName) {
  340. return msg + " (Db=" + db.getName() + ";Index=" + idxName + ")";
  341. }
  342. /**
  343. * Information about a foreign key reference defined in an index (when
  344. * referential integrity should be enforced).
  345. */
  346. public static class ForeignKeyReference
  347. {
  348. private final byte _tableType;
  349. private final int _otherIndexNumber;
  350. private final int _otherTablePageNumber;
  351. private final boolean _cascadeUpdates;
  352. private final boolean _cascadeDeletes;
  353. private final boolean _cascadeNull;
  354. public ForeignKeyReference(
  355. byte tableType, int otherIndexNumber, int otherTablePageNumber,
  356. boolean cascadeUpdates, boolean cascadeDeletes, boolean cascadeNull)
  357. {
  358. _tableType = tableType;
  359. _otherIndexNumber = otherIndexNumber;
  360. _otherTablePageNumber = otherTablePageNumber;
  361. _cascadeUpdates = cascadeUpdates;
  362. _cascadeDeletes = cascadeDeletes;
  363. _cascadeNull = cascadeNull;
  364. }
  365. public byte getTableType() {
  366. return _tableType;
  367. }
  368. public boolean isPrimaryTable() {
  369. return(getTableType() == PRIMARY_TABLE_TYPE);
  370. }
  371. public int getOtherIndexNumber() {
  372. return _otherIndexNumber;
  373. }
  374. public int getOtherTablePageNumber() {
  375. return _otherTablePageNumber;
  376. }
  377. public boolean isCascadeUpdates() {
  378. return _cascadeUpdates;
  379. }
  380. public boolean isCascadeDeletes() {
  381. return _cascadeDeletes;
  382. }
  383. public boolean isCascadeNullOnDelete() {
  384. return _cascadeNull;
  385. }
  386. @Override
  387. public String toString() {
  388. return CustomToStringStyle.builder(this)
  389. .append("otherIndexNumber", _otherIndexNumber)
  390. .append("otherTablePageNum", _otherTablePageNumber)
  391. .append("isPrimaryTable", isPrimaryTable())
  392. .append("isCascadeUpdates", isCascadeUpdates())
  393. .append("isCascadeDeletes", isCascadeDeletes())
  394. .append("isCascadeNullOnDelete", isCascadeNullOnDelete())
  395. .toString();
  396. }
  397. }
  398. }