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.

TableCreator.java 9.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. /*
  2. Copyright (c) 2011 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.util.ArrayList;
  16. import java.util.Collections;
  17. import java.util.EnumSet;
  18. import java.util.HashSet;
  19. import java.util.IdentityHashMap;
  20. import java.util.List;
  21. import java.util.Map;
  22. import java.util.Set;
  23. import com.healthmarketscience.jackcess.ColumnBuilder;
  24. import com.healthmarketscience.jackcess.DataType;
  25. import com.healthmarketscience.jackcess.IndexBuilder;
  26. import com.healthmarketscience.jackcess.PropertyMap;
  27. import com.healthmarketscience.jackcess.TableBuilder;
  28. /**
  29. * Helper class used to maintain state during table creation.
  30. *
  31. * @author James Ahlborn
  32. * @usage _advanced_class_
  33. */
  34. public class TableCreator extends TableMutator
  35. {
  36. private String _name;
  37. private List<ColumnBuilder> _columns;
  38. private List<IndexBuilder> _indexes;
  39. private final List<IndexDataState> _indexDataStates =
  40. new ArrayList<IndexDataState>();
  41. private final Map<ColumnBuilder,ColumnState> _columnStates =
  42. new IdentityHashMap<ColumnBuilder,ColumnState>();
  43. private final List<ColumnBuilder> _lvalCols = new ArrayList<ColumnBuilder>();
  44. private int _tdefPageNumber = PageChannel.INVALID_PAGE_NUMBER;
  45. private int _umapPageNumber = PageChannel.INVALID_PAGE_NUMBER;
  46. private int _indexCount;
  47. private int _logicalIndexCount;
  48. public TableCreator(DatabaseImpl database) {
  49. super(database);
  50. }
  51. public String getName() {
  52. return _name;
  53. }
  54. @Override
  55. String getTableName() {
  56. return getName();
  57. }
  58. @Override
  59. public int getTdefPageNumber() {
  60. return _tdefPageNumber;
  61. }
  62. public int getUmapPageNumber() {
  63. return _umapPageNumber;
  64. }
  65. public List<ColumnBuilder> getColumns() {
  66. return _columns;
  67. }
  68. public List<IndexBuilder> getIndexes() {
  69. return _indexes;
  70. }
  71. public boolean hasIndexes() {
  72. return !_indexes.isEmpty();
  73. }
  74. public int getIndexCount() {
  75. return _indexCount;
  76. }
  77. public int getLogicalIndexCount() {
  78. return _logicalIndexCount;
  79. }
  80. @Override
  81. public IndexDataState getIndexDataState(IndexBuilder idx) {
  82. for(IndexDataState idxDataState : _indexDataStates) {
  83. for(IndexBuilder curIdx : idxDataState.getIndexes()) {
  84. if(idx == curIdx) {
  85. return idxDataState;
  86. }
  87. }
  88. }
  89. throw new IllegalStateException(withErrorContext(
  90. "could not find state for index"));
  91. }
  92. public List<IndexDataState> getIndexDataStates() {
  93. return _indexDataStates;
  94. }
  95. @Override
  96. public ColumnState getColumnState(ColumnBuilder col) {
  97. return _columnStates.get(col);
  98. }
  99. public List<ColumnBuilder> getLongValueColumns() {
  100. return _lvalCols;
  101. }
  102. @Override
  103. short getColumnNumber(String colName) {
  104. for(ColumnBuilder col : _columns) {
  105. if(col.getName().equalsIgnoreCase(colName)) {
  106. return col.getColumnNumber();
  107. }
  108. }
  109. return IndexData.COLUMN_UNUSED;
  110. }
  111. /**
  112. * @return The number of variable length columns which are not long values
  113. * found in the list
  114. * @usage _advanced_method_
  115. */
  116. public short countNonLongVariableLength() {
  117. short rtn = 0;
  118. for (ColumnBuilder col : _columns) {
  119. if (col.isVariableLength() && !col.getType().isLongValue()) {
  120. rtn++;
  121. }
  122. }
  123. return rtn;
  124. }
  125. /**
  126. * Creates the table in the database.
  127. * @usage _advanced_method_
  128. */
  129. public TableImpl createTable(TableBuilder table) throws IOException {
  130. _name = table.getName();
  131. _columns = table.getColumns();
  132. _indexes = table.getIndexes();
  133. if(_indexes == null) {
  134. _indexes = Collections.<IndexBuilder>emptyList();
  135. }
  136. validate();
  137. // assign column numbers and do some assorted column bookkeeping
  138. short columnNumber = (short) 0;
  139. for(ColumnBuilder col : _columns) {
  140. col.setColumnNumber(columnNumber++);
  141. if(col.getType().isLongValue()) {
  142. _lvalCols.add(col);
  143. // only lval columns need extra state
  144. _columnStates.put(col, new ColumnState());
  145. }
  146. }
  147. if(hasIndexes()) {
  148. // sort out index numbers (and backing index data).
  149. for(IndexBuilder idx : _indexes) {
  150. idx.setIndexNumber(_logicalIndexCount++);
  151. findIndexDataState(idx);
  152. }
  153. }
  154. getPageChannel().startWrite();
  155. try {
  156. // reserve some pages
  157. _tdefPageNumber = reservePageNumber();
  158. _umapPageNumber = reservePageNumber();
  159. //Write the tdef page to disk.
  160. TableImpl.writeTableDefinition(this);
  161. // update the database with the new table info
  162. getDatabase().addNewTable(_name, _tdefPageNumber, DatabaseImpl.TYPE_TABLE,
  163. null, null);
  164. TableImpl newTable = getDatabase().getTable(_name);
  165. // add any table properties
  166. boolean addedProps = false;
  167. Map<String,PropertyMap.Property> props = table.getProperties();
  168. if(props != null) {
  169. newTable.getProperties().putAll(props.values());
  170. addedProps = true;
  171. }
  172. for(ColumnBuilder cb : _columns) {
  173. Map<String,PropertyMap.Property> colProps = cb.getProperties();
  174. if(colProps != null) {
  175. newTable.getColumn(cb.getName()).getProperties()
  176. .putAll(colProps.values());
  177. addedProps = true;
  178. }
  179. }
  180. // all table and column props are saved together
  181. if(addedProps) {
  182. newTable.getProperties().save();
  183. }
  184. return newTable;
  185. } finally {
  186. getPageChannel().finishWrite();
  187. }
  188. }
  189. private IndexDataState findIndexDataState(IndexBuilder idx) {
  190. // search for an index which matches the given index (in terms of the
  191. // backing data)
  192. for(IndexDataState idxDataState : _indexDataStates) {
  193. if(sameIndexData(idxDataState.getFirstIndex(), idx)) {
  194. idxDataState.addIndex(idx);
  195. return idxDataState;
  196. }
  197. }
  198. // no matches found, need new index data state
  199. IndexDataState idxDataState = new IndexDataState();
  200. idxDataState.setIndexDataNumber(_indexCount++);
  201. idxDataState.addIndex(idx);
  202. _indexDataStates.add(idxDataState);
  203. return idxDataState;
  204. }
  205. /**
  206. * Validates the new table information before attempting creation.
  207. */
  208. private void validate() throws IOException {
  209. getDatabase().validateNewTableName(_name);
  210. if((_columns == null) || _columns.isEmpty()) {
  211. throw new IllegalArgumentException(withErrorContext(
  212. "Cannot create table with no columns"));
  213. }
  214. if(_columns.size() > getFormat().MAX_COLUMNS_PER_TABLE) {
  215. throw new IllegalArgumentException(withErrorContext(
  216. "Cannot create table with more than " +
  217. getFormat().MAX_COLUMNS_PER_TABLE + " columns"));
  218. }
  219. Set<String> colNames = new HashSet<String>();
  220. // next, validate the column definitions
  221. for(ColumnBuilder column : _columns) {
  222. validateColumn(colNames, column);
  223. }
  224. List<ColumnBuilder> autoCols = getAutoNumberColumns();
  225. if(autoCols.size() > 1) {
  226. // for most autonumber types, we can only have one of each type
  227. Set<DataType> autoTypes = EnumSet.noneOf(DataType.class);
  228. for(ColumnBuilder c : autoCols) {
  229. validateAutoNumberColumn(autoTypes, c);
  230. }
  231. }
  232. if(hasIndexes()) {
  233. if(_indexes.size() > getFormat().MAX_INDEXES_PER_TABLE) {
  234. throw new IllegalArgumentException(withErrorContext(
  235. "Cannot create table with more than " +
  236. getFormat().MAX_INDEXES_PER_TABLE + " indexes"));
  237. }
  238. // now, validate the indexes
  239. Set<String> idxNames = new HashSet<String>();
  240. boolean foundPk[] = new boolean[1];
  241. for(IndexBuilder index : _indexes) {
  242. validateIndex(colNames, idxNames, foundPk, index);
  243. }
  244. }
  245. }
  246. private List<ColumnBuilder> getAutoNumberColumns()
  247. {
  248. List<ColumnBuilder> autoCols = new ArrayList<ColumnBuilder>(1);
  249. for(ColumnBuilder c : _columns) {
  250. if(c.isAutoNumber()) {
  251. autoCols.add(c);
  252. }
  253. }
  254. return autoCols;
  255. }
  256. private static boolean sameIndexData(IndexBuilder idx1, IndexBuilder idx2) {
  257. // index data can be combined if flags match and columns (and col flags)
  258. // match
  259. if(idx1.getFlags() != idx2.getFlags()) {
  260. return false;
  261. }
  262. if(idx1.getColumns().size() != idx2.getColumns().size()) {
  263. return false;
  264. }
  265. for(int i = 0; i < idx1.getColumns().size(); ++i) {
  266. IndexBuilder.Column col1 = idx1.getColumns().get(i);
  267. IndexBuilder.Column col2 = idx2.getColumns().get(i);
  268. if(!sameIndexData(col1, col2)) {
  269. return false;
  270. }
  271. }
  272. return true;
  273. }
  274. private static boolean sameIndexData(
  275. IndexBuilder.Column col1, IndexBuilder.Column col2) {
  276. return (col1.getName().equals(col2.getName()) &&
  277. (col1.getFlags() == col2.getFlags()));
  278. }
  279. private String withErrorContext(String msg) {
  280. return msg + "(Table=" + getName() + ")";
  281. }
  282. }