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.

FKEnforcer.java 9.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. /*
  2. Copyright (c) 2012 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.Arrays;
  17. import java.util.Collections;
  18. import java.util.Iterator;
  19. import java.util.List;
  20. import java.util.Set;
  21. import java.util.TreeSet;
  22. import com.healthmarketscience.jackcess.Column;
  23. import com.healthmarketscience.jackcess.ConstraintViolationException;
  24. import com.healthmarketscience.jackcess.Index;
  25. import com.healthmarketscience.jackcess.IndexCursor;
  26. import com.healthmarketscience.jackcess.Row;
  27. import com.healthmarketscience.jackcess.Table;
  28. import com.healthmarketscience.jackcess.util.CaseInsensitiveColumnMatcher;
  29. import com.healthmarketscience.jackcess.util.ColumnMatcher;
  30. import com.healthmarketscience.jackcess.util.Joiner;
  31. /**
  32. * Utility class used by Table to enforce foreign-key relationships (if
  33. * enabled).
  34. *
  35. * @author James Ahlborn
  36. * @usage _advanced_class_
  37. */
  38. final class FKEnforcer
  39. {
  40. // fk constraints always work with indexes, which are always
  41. // case-insensitive
  42. private static final ColumnMatcher MATCHER =
  43. CaseInsensitiveColumnMatcher.INSTANCE;
  44. private final TableImpl _table;
  45. private final List<ColumnImpl> _cols;
  46. private List<Joiner> _primaryJoinersChkUp;
  47. private List<Joiner> _primaryJoinersChkDel;
  48. private List<Joiner> _primaryJoinersDoUp;
  49. private List<Joiner> _primaryJoinersDoDel;
  50. private List<Joiner> _secondaryJoiners;
  51. FKEnforcer(TableImpl table) {
  52. _table = table;
  53. // at this point, only init the index columns
  54. Set<ColumnImpl> cols = new TreeSet<ColumnImpl>();
  55. for(IndexImpl idx : _table.getIndexes()) {
  56. IndexImpl.ForeignKeyReference ref = idx.getReference();
  57. if(ref != null) {
  58. // compile an ordered list of all columns in this table which are
  59. // involved in foreign key relationships with other tables
  60. for(IndexData.ColumnDescriptor iCol : idx.getColumns()) {
  61. cols.add(iCol.getColumn());
  62. }
  63. }
  64. }
  65. _cols = !cols.isEmpty() ?
  66. Collections.unmodifiableList(new ArrayList<ColumnImpl>(cols)) :
  67. Collections.<ColumnImpl>emptyList();
  68. }
  69. /**
  70. * Does secondary initialization, if necessary.
  71. */
  72. private void initialize() throws IOException {
  73. if(_secondaryJoiners != null) {
  74. // already initialized
  75. return;
  76. }
  77. // initialize all the joiners
  78. _primaryJoinersChkUp = new ArrayList<Joiner>(1);
  79. _primaryJoinersChkDel = new ArrayList<Joiner>(1);
  80. _primaryJoinersDoUp = new ArrayList<Joiner>(1);
  81. _primaryJoinersDoDel = new ArrayList<Joiner>(1);
  82. _secondaryJoiners = new ArrayList<Joiner>(1);
  83. for(IndexImpl idx : _table.getIndexes()) {
  84. IndexImpl.ForeignKeyReference ref = idx.getReference();
  85. if(ref != null) {
  86. Joiner joiner = Joiner.create(idx);
  87. if(ref.isPrimaryTable()) {
  88. if(ref.isCascadeUpdates()) {
  89. _primaryJoinersDoUp.add(joiner);
  90. } else {
  91. _primaryJoinersChkUp.add(joiner);
  92. }
  93. if(ref.isCascadeDeletes()) {
  94. _primaryJoinersDoDel.add(joiner);
  95. } else {
  96. _primaryJoinersChkDel.add(joiner);
  97. }
  98. } else {
  99. _secondaryJoiners.add(joiner);
  100. }
  101. }
  102. }
  103. }
  104. /**
  105. * Handles foregn-key constraints when adding a row.
  106. *
  107. * @param row new row in the Table's row format, including all values used
  108. * in any foreign-key relationships
  109. */
  110. public void addRow(Object[] row) throws IOException {
  111. if(!enforcing()) {
  112. return;
  113. }
  114. initialize();
  115. for(Joiner joiner : _secondaryJoiners) {
  116. requirePrimaryValues(joiner, row);
  117. }
  118. }
  119. /**
  120. * Handles foregn-key constraints when updating a row.
  121. *
  122. * @param oldRow old row in the Table's row format, including all values
  123. * used in any foreign-key relationships
  124. * @param newRow new row in the Table's row format, including all values
  125. * used in any foreign-key relationships
  126. */
  127. public void updateRow(Object[] oldRow, Object[] newRow) throws IOException {
  128. if(!enforcing()) {
  129. return;
  130. }
  131. if(!anyUpdates(oldRow, newRow)) {
  132. // no changes were made to any relevant columns
  133. return;
  134. }
  135. initialize();
  136. SharedState ss = _table.getDatabase().getFKEnforcerSharedState();
  137. if(ss.isUpdating()) {
  138. // we only check the primary relationships for the "top-level" of an
  139. // update operation. in nested levels we are only ever changing the fk
  140. // values themselves, so we always know the new values are valid.
  141. for(Joiner joiner : _secondaryJoiners) {
  142. if(anyUpdates(joiner, oldRow, newRow)) {
  143. requirePrimaryValues(joiner, newRow);
  144. }
  145. }
  146. }
  147. ss.pushUpdate();
  148. try {
  149. // now, check the tables for which we are the primary table in the
  150. // relationship (but not cascading)
  151. for(Joiner joiner : _primaryJoinersChkUp) {
  152. if(anyUpdates(joiner, oldRow, newRow)) {
  153. requireNoSecondaryValues(joiner, oldRow);
  154. }
  155. }
  156. // lastly, update the tables for which we are the primary table in the
  157. // relationship
  158. for(Joiner joiner : _primaryJoinersDoUp) {
  159. if(anyUpdates(joiner, oldRow, newRow)) {
  160. updateSecondaryValues(joiner, oldRow, newRow);
  161. }
  162. }
  163. } finally {
  164. ss.popUpdate();
  165. }
  166. }
  167. /**
  168. * Handles foregn-key constraints when deleting a row.
  169. *
  170. * @param row old row in the Table's row format, including all values used
  171. * in any foreign-key relationships
  172. */
  173. public void deleteRow(Object[] row) throws IOException {
  174. if(!enforcing()) {
  175. return;
  176. }
  177. initialize();
  178. // first, check the tables for which we are the primary table in the
  179. // relationship (but not cascading)
  180. for(Joiner joiner : _primaryJoinersChkDel) {
  181. requireNoSecondaryValues(joiner, row);
  182. }
  183. // lastly, delete from the tables for which we are the primary table in
  184. // the relationship
  185. for(Joiner joiner : _primaryJoinersDoDel) {
  186. joiner.deleteRows(row);
  187. }
  188. }
  189. private static void requirePrimaryValues(Joiner joiner, Object[] row)
  190. throws IOException
  191. {
  192. // ensure that the relevant rows exist in the primary tables for which
  193. // this table is a secondary table.
  194. if(!joiner.hasRows(row)) {
  195. throw new ConstraintViolationException(
  196. "Adding new row " + Arrays.asList(row) + " violates constraint " +
  197. joiner.toFKString());
  198. }
  199. }
  200. private static void requireNoSecondaryValues(Joiner joiner, Object[] row)
  201. throws IOException
  202. {
  203. // ensure that no rows exist in the secondary table for which this table is
  204. // the primary table.
  205. if(joiner.hasRows(row)) {
  206. throw new ConstraintViolationException(
  207. "Removing old row " + Arrays.asList(row) + " violates constraint " +
  208. joiner.toFKString());
  209. }
  210. }
  211. private static void updateSecondaryValues(Joiner joiner, Object[] oldFromRow,
  212. Object[] newFromRow)
  213. throws IOException
  214. {
  215. IndexCursor toCursor = joiner.getToCursor();
  216. List<? extends Index.Column> fromCols = joiner.getColumns();
  217. List<? extends Index.Column> toCols = joiner.getToIndex().getColumns();
  218. Object[] toRow = new Object[joiner.getToTable().getColumnCount()];
  219. for(Iterator<Row> iter = joiner.findRows(oldFromRow)
  220. .setColumnNames(Collections.<String>emptySet())
  221. .iterator(); iter.hasNext(); ) {
  222. iter.next();
  223. // create update row for "to" table
  224. Arrays.fill(toRow, Column.KEEP_VALUE);
  225. for(int i = 0; i < fromCols.size(); ++i) {
  226. Object val = fromCols.get(i).getColumn().getRowValue(newFromRow);
  227. toCols.get(i).getColumn().setRowValue(toRow, val);
  228. }
  229. toCursor.updateCurrentRow(toRow);
  230. }
  231. }
  232. private boolean anyUpdates(Object[] oldRow, Object[] newRow) {
  233. for(ColumnImpl col : _cols) {
  234. if(!MATCHER.matches(_table, col.getName(),
  235. col.getRowValue(oldRow), col.getRowValue(newRow))) {
  236. return true;
  237. }
  238. }
  239. return false;
  240. }
  241. private static boolean anyUpdates(Joiner joiner,Object[] oldRow,
  242. Object[] newRow)
  243. {
  244. Table fromTable = joiner.getFromTable();
  245. for(Index.Column iCol : joiner.getColumns()) {
  246. Column col = iCol.getColumn();
  247. if(!MATCHER.matches(fromTable, col.getName(),
  248. col.getRowValue(oldRow), col.getRowValue(newRow))) {
  249. return true;
  250. }
  251. }
  252. return false;
  253. }
  254. private boolean enforcing() {
  255. return _table.getDatabase().isEnforceForeignKeys();
  256. }
  257. static SharedState initSharedState() {
  258. return new SharedState();
  259. }
  260. /**
  261. * Shared state used by all FKEnforcers for a given Database.
  262. */
  263. static final class SharedState
  264. {
  265. /** current depth of cascading update calls across one or more tables */
  266. private int _updateDepth;
  267. private SharedState() {
  268. }
  269. public boolean isUpdating() {
  270. return (_updateDepth == 0);
  271. }
  272. public void pushUpdate() {
  273. ++_updateDepth;
  274. }
  275. public void popUpdate() {
  276. --_updateDepth;
  277. }
  278. }
  279. }