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.

TableUpdater.java 9.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. /*
  2. Copyright (c) 2016 James Ahlborn
  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.ArrayList;
  17. import java.util.EnumSet;
  18. import java.util.HashSet;
  19. import java.util.List;
  20. import java.util.Set;
  21. import com.healthmarketscience.jackcess.ColumnBuilder;
  22. import com.healthmarketscience.jackcess.DataType;
  23. import com.healthmarketscience.jackcess.IndexBuilder;
  24. /**
  25. * Helper class used to maintain state during table mutation.
  26. *
  27. * @author James Ahlborn
  28. * @usage _advanced_class_
  29. */
  30. public class TableUpdater extends TableMutator
  31. {
  32. private final TableImpl _table;
  33. private ColumnBuilder _column;
  34. private IndexBuilder _index;
  35. private int _origTdefLen;
  36. private int _addedTdefLen;
  37. private List<Integer> _nextPages = new ArrayList<Integer>(1);
  38. private ColumnState _colState;
  39. private IndexDataState _idxDataState;
  40. private IndexImpl.ForeignKeyReference _fkReference;
  41. public TableUpdater(TableImpl table) {
  42. super(table.getDatabase());
  43. _table = table;
  44. }
  45. public ColumnBuilder getColumn() {
  46. return _column;
  47. }
  48. public IndexBuilder getIndex() {
  49. return _index;
  50. }
  51. @Override
  52. String getTableName() {
  53. return _table.getName();
  54. }
  55. @Override
  56. public int getTdefPageNumber() {
  57. return _table.getTableDefPageNumber();
  58. }
  59. @Override
  60. short getColumnNumber(String colName) {
  61. for(ColumnImpl col : _table.getColumns()) {
  62. if(col.getName().equalsIgnoreCase(colName)) {
  63. return col.getColumnNumber();
  64. }
  65. }
  66. return IndexData.COLUMN_UNUSED;
  67. }
  68. @Override
  69. public ColumnState getColumnState(ColumnBuilder col) {
  70. return ((col == _column) ? _colState : null);
  71. }
  72. @Override
  73. public IndexDataState getIndexDataState(IndexBuilder idx) {
  74. return ((idx == _index) ? _idxDataState : null);
  75. }
  76. void setForeignKey(IndexImpl.ForeignKeyReference fkReference) {
  77. _fkReference = fkReference;
  78. }
  79. @Override
  80. public IndexImpl.ForeignKeyReference getForeignKey(IndexBuilder idx) {
  81. return ((idx == _index) ? _fkReference : null);
  82. }
  83. int getAddedTdefLen() {
  84. return _addedTdefLen;
  85. }
  86. void addTdefLen(int add) {
  87. _addedTdefLen += add;
  88. }
  89. void setOrigTdefLen(int len) {
  90. _origTdefLen = len;
  91. }
  92. List<Integer> getNextPages() {
  93. return _nextPages;
  94. }
  95. void resetTdefInfo() {
  96. _addedTdefLen = 0;
  97. _origTdefLen = 0;
  98. _nextPages.clear();
  99. }
  100. public ColumnImpl addColumn(ColumnBuilder column) throws IOException {
  101. _column = column;
  102. validateAddColumn();
  103. // assign column number and do some assorted column bookkeeping
  104. short columnNumber = (short)_table.getMaxColumnCount();
  105. _column.setColumnNumber(columnNumber);
  106. if(_column.getType().isLongValue()) {
  107. _colState = new ColumnState();
  108. }
  109. getPageChannel().startExclusiveWrite();
  110. try {
  111. return _table.mutateAddColumn(this);
  112. } finally {
  113. getPageChannel().finishWrite();
  114. }
  115. }
  116. public IndexImpl addIndex(IndexBuilder index) throws IOException {
  117. return addIndex(index, false, (byte)0, (byte)0);
  118. }
  119. IndexImpl addIndex(IndexBuilder index, boolean isInternal, byte ignoreIdxFlags,
  120. byte ignoreColFlags)
  121. throws IOException
  122. {
  123. _index = index;
  124. if(!isInternal) {
  125. validateAddIndex();
  126. }
  127. // assign index number and do some assorted index bookkeeping
  128. int indexNumber = _table.getLogicalIndexCount();
  129. _index.setIndexNumber(indexNumber);
  130. // initialize backing index state
  131. initIndexDataState(ignoreIdxFlags, ignoreColFlags);
  132. if(!isInternal) {
  133. getPageChannel().startExclusiveWrite();
  134. } else {
  135. getPageChannel().startWrite();
  136. }
  137. try {
  138. if(_idxDataState.getIndexDataNumber() == _table.getIndexCount()) {
  139. // we need a new backing index data
  140. _table.mutateAddIndexData(this);
  141. // we need to modify the table def again when adding the Index, so reset
  142. resetTdefInfo();
  143. }
  144. return _table.mutateAddIndex(this);
  145. } finally {
  146. getPageChannel().finishWrite();
  147. }
  148. }
  149. boolean validateUpdatedTdef(ByteBuffer tableBuffer) {
  150. // sanity check the updates
  151. return((_origTdefLen + _addedTdefLen) == tableBuffer.limit());
  152. }
  153. private void validateAddColumn() {
  154. if(_column == null) {
  155. throw new IllegalArgumentException(withErrorContext(
  156. "Cannot add column with no column"));
  157. }
  158. if((_table.getColumnCount() + 1) > getFormat().MAX_COLUMNS_PER_TABLE) {
  159. throw new IllegalArgumentException(withErrorContext(
  160. "Cannot add column to table with " +
  161. getFormat().MAX_COLUMNS_PER_TABLE + " columns"));
  162. }
  163. Set<String> colNames = getColumnNames();
  164. // next, validate the column definition
  165. validateColumn(colNames, _column);
  166. if(_column.isAutoNumber()) {
  167. // for most autonumber types, we can only have one of each type
  168. Set<DataType> autoTypes = EnumSet.noneOf(DataType.class);
  169. for(ColumnImpl column : _table.getAutoNumberColumns()) {
  170. autoTypes.add(column.getType());
  171. }
  172. validateAutoNumberColumn(autoTypes, _column);
  173. }
  174. }
  175. private void validateAddIndex() {
  176. if(_index == null) {
  177. throw new IllegalArgumentException(withErrorContext(
  178. "Cannot add index with no index"));
  179. }
  180. if((_table.getLogicalIndexCount() + 1) > getFormat().MAX_INDEXES_PER_TABLE) {
  181. throw new IllegalArgumentException(withErrorContext(
  182. "Cannot add index to table with " +
  183. getFormat().MAX_INDEXES_PER_TABLE + " indexes"));
  184. }
  185. boolean foundPk[] = new boolean[1];
  186. Set<String> idxNames = getIndexNames(_table, foundPk);
  187. // next, validate the index definition
  188. validateIndex(getColumnNames(), idxNames, foundPk, _index);
  189. }
  190. private Set<String> getColumnNames() {
  191. Set<String> colNames = new HashSet<String>();
  192. for(ColumnImpl column : _table.getColumns()) {
  193. colNames.add(column.getName().toUpperCase());
  194. }
  195. return colNames;
  196. }
  197. static Set<String> getIndexNames(TableImpl table, boolean[] foundPk) {
  198. Set<String> idxNames = new HashSet<String>();
  199. for(IndexImpl index : table.getIndexes()) {
  200. idxNames.add(index.getName().toUpperCase());
  201. if(index.isPrimaryKey() && (foundPk != null)) {
  202. foundPk[0] = true;
  203. }
  204. }
  205. return idxNames;
  206. }
  207. private void initIndexDataState(byte ignoreIdxFlags, byte ignoreColFlags) {
  208. _idxDataState = new IndexDataState();
  209. _idxDataState.addIndex(_index);
  210. // search for an existing index which matches the given index (in terms of
  211. // the backing data)
  212. IndexData idxData = findIndexData(
  213. _index, _table, ignoreIdxFlags, ignoreColFlags);
  214. int idxDataNumber = ((idxData != null) ?
  215. idxData.getIndexDataNumber() :
  216. _table.getIndexCount());
  217. _idxDataState.setIndexDataNumber(idxDataNumber);
  218. }
  219. static IndexData findIndexData(IndexBuilder idx, TableImpl table,
  220. byte ignoreIdxFlags, byte ignoreColFlags)
  221. {
  222. for(IndexData idxData : table.getIndexDatas()) {
  223. if(sameIndexData(idx, idxData, ignoreIdxFlags, ignoreColFlags)) {
  224. return idxData;
  225. }
  226. }
  227. return null;
  228. }
  229. private static boolean sameIndexData(IndexBuilder idx1, IndexData idx2,
  230. byte ignoreIdxFlags, byte ignoreColFlags) {
  231. // index data can be combined if flags match and columns (and col flags)
  232. // match
  233. if((idx1.getFlags() | ignoreIdxFlags) !=
  234. (idx2.getIndexFlags() | ignoreIdxFlags)) {
  235. return false;
  236. }
  237. if(idx1.getColumns().size() != idx2.getColumns().size()) {
  238. return false;
  239. }
  240. for(int i = 0; i < idx1.getColumns().size(); ++i) {
  241. IndexBuilder.Column col1 = idx1.getColumns().get(i);
  242. IndexData.ColumnDescriptor col2 = idx2.getColumns().get(i);
  243. if(!sameIndexData(col1, col2, ignoreColFlags)) {
  244. return false;
  245. }
  246. }
  247. return true;
  248. }
  249. private static boolean sameIndexData(
  250. IndexBuilder.Column col1, IndexData.ColumnDescriptor col2,
  251. int ignoreColFlags) {
  252. return (col1.getName().equals(col2.getName()) &&
  253. ((col1.getFlags() | ignoreColFlags) ==
  254. (col2.getFlags() | ignoreColFlags)));
  255. }
  256. @Override
  257. protected String withErrorContext(String msg) {
  258. String objStr = "";
  259. if(_column != null) {
  260. objStr = ";Column=" + _column.getName();
  261. } else if(_index != null) {
  262. objStr = ";Index=" + _index.getName();
  263. }
  264. return msg + "(Table=" + _table.getName() + objStr + ")";
  265. }
  266. }