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ů.

FKEnforcer.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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 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> _primaryJoinersDoNull;
  51. private List<Joiner> _secondaryJoiners;
  52. FKEnforcer(TableImpl table) {
  53. _table = table;
  54. // at this point, only init the index columns
  55. initColumns();
  56. }
  57. private void initColumns() {
  58. Set<ColumnImpl> cols = new TreeSet<ColumnImpl>();
  59. for(IndexImpl idx : _table.getIndexes()) {
  60. IndexImpl.ForeignKeyReference ref = idx.getReference();
  61. if(ref != null) {
  62. // compile an ordered list of all columns in this table which are
  63. // involved in foreign key relationships with other tables
  64. for(IndexData.ColumnDescriptor iCol : idx.getColumns()) {
  65. cols.add(iCol.getColumn());
  66. }
  67. }
  68. }
  69. _cols = !cols.isEmpty() ?
  70. Collections.unmodifiableList(new ArrayList<ColumnImpl>(cols)) :
  71. Collections.<ColumnImpl>emptyList();
  72. }
  73. /**
  74. * Resets the internals of this FKEnforcer (for post-table modification)
  75. */
  76. void reset() {
  77. // columns to enforce may have changed
  78. initColumns();
  79. // clear any existing joiners (will be re-created on next use)
  80. _primaryJoinersChkUp = null;
  81. _primaryJoinersChkDel = null;
  82. _primaryJoinersDoUp = null;
  83. _primaryJoinersDoDel = null;
  84. _primaryJoinersDoNull = null;
  85. _secondaryJoiners = null;
  86. }
  87. /**
  88. * Does secondary initialization, if necessary.
  89. */
  90. private void initialize() throws IOException {
  91. if(_secondaryJoiners != null) {
  92. // already initialized
  93. return;
  94. }
  95. // initialize all the joiners
  96. _primaryJoinersChkUp = new ArrayList<Joiner>(1);
  97. _primaryJoinersChkDel = new ArrayList<Joiner>(1);
  98. _primaryJoinersDoUp = new ArrayList<Joiner>(1);
  99. _primaryJoinersDoDel = new ArrayList<Joiner>(1);
  100. _primaryJoinersDoNull = new ArrayList<Joiner>(1);
  101. _secondaryJoiners = new ArrayList<Joiner>(1);
  102. for(IndexImpl idx : _table.getIndexes()) {
  103. IndexImpl.ForeignKeyReference ref = idx.getReference();
  104. if(ref != null) {
  105. Joiner joiner = Joiner.create(idx);
  106. if(ref.isPrimaryTable()) {
  107. if(ref.isCascadeUpdates()) {
  108. _primaryJoinersDoUp.add(joiner);
  109. } else {
  110. _primaryJoinersChkUp.add(joiner);
  111. }
  112. if(ref.isCascadeDeletes()) {
  113. _primaryJoinersDoDel.add(joiner);
  114. } else if(ref.isCascadeNullOnDelete()) {
  115. _primaryJoinersDoNull.add(joiner);
  116. } else {
  117. _primaryJoinersChkDel.add(joiner);
  118. }
  119. } else {
  120. _secondaryJoiners.add(joiner);
  121. }
  122. }
  123. }
  124. }
  125. /**
  126. * Handles foregn-key constraints when adding a row.
  127. *
  128. * @param row new row in the Table's row format, including all values used
  129. * in any foreign-key relationships
  130. */
  131. public void addRow(Object[] row) throws IOException {
  132. if(!enforcing()) {
  133. return;
  134. }
  135. initialize();
  136. for(Joiner joiner : _secondaryJoiners) {
  137. requirePrimaryValues(joiner, row);
  138. }
  139. }
  140. /**
  141. * Handles foregn-key constraints when updating a row.
  142. *
  143. * @param oldRow old row in the Table's row format, including all values
  144. * used in any foreign-key relationships
  145. * @param newRow new row in the Table's row format, including all values
  146. * used in any foreign-key relationships
  147. */
  148. public void updateRow(Object[] oldRow, Object[] newRow) throws IOException {
  149. if(!enforcing()) {
  150. return;
  151. }
  152. if(!anyUpdates(oldRow, newRow)) {
  153. // no changes were made to any relevant columns
  154. return;
  155. }
  156. initialize();
  157. SharedState ss = _table.getDatabase().getFKEnforcerSharedState();
  158. if(ss.isUpdating()) {
  159. // we only check the primary relationships for the "top-level" of an
  160. // update operation. in nested levels we are only ever changing the fk
  161. // values themselves, so we always know the new values are valid.
  162. for(Joiner joiner : _secondaryJoiners) {
  163. if(anyUpdates(joiner, oldRow, newRow)) {
  164. requirePrimaryValues(joiner, newRow);
  165. }
  166. }
  167. }
  168. ss.pushUpdate();
  169. try {
  170. // now, check the tables for which we are the primary table in the
  171. // relationship (but not cascading)
  172. for(Joiner joiner : _primaryJoinersChkUp) {
  173. if(anyUpdates(joiner, oldRow, newRow)) {
  174. requireNoSecondaryValues(joiner, oldRow);
  175. }
  176. }
  177. // lastly, update the tables for which we are the primary table in the
  178. // relationship
  179. for(Joiner joiner : _primaryJoinersDoUp) {
  180. if(anyUpdates(joiner, oldRow, newRow)) {
  181. updateSecondaryValues(joiner, oldRow, newRow);
  182. }
  183. }
  184. } finally {
  185. ss.popUpdate();
  186. }
  187. }
  188. /**
  189. * Handles foregn-key constraints when deleting a row.
  190. *
  191. * @param row old row in the Table's row format, including all values used
  192. * in any foreign-key relationships
  193. */
  194. public void deleteRow(Object[] row) throws IOException {
  195. if(!enforcing()) {
  196. return;
  197. }
  198. initialize();
  199. // first, check the tables for which we are the primary table in the
  200. // relationship (but not cascading)
  201. for(Joiner joiner : _primaryJoinersChkDel) {
  202. requireNoSecondaryValues(joiner, row);
  203. }
  204. // next, delete from the tables for which we are the primary table in
  205. // the relationship
  206. for(Joiner joiner : _primaryJoinersDoDel) {
  207. joiner.deleteRows(row);
  208. }
  209. // lastly, null the tables for which we are the primary table in
  210. // the relationship
  211. for(Joiner joiner : _primaryJoinersDoNull) {
  212. nullSecondaryValues(joiner, row);
  213. }
  214. }
  215. private static void requirePrimaryValues(Joiner joiner, Object[] row)
  216. throws IOException
  217. {
  218. // ensure that the relevant rows exist in the primary tables for which
  219. // this table is a secondary table. however, null values are allowed
  220. if(!areNull(joiner, row) && !joiner.hasRows(row)) {
  221. throw new ConstraintViolationException(
  222. "Adding new row " + Arrays.asList(row) + " violates constraint " +
  223. joiner.toFKString());
  224. }
  225. }
  226. private static void requireNoSecondaryValues(Joiner joiner, Object[] row)
  227. throws IOException
  228. {
  229. // ensure that no rows exist in the secondary table for which this table is
  230. // the primary table.
  231. if(joiner.hasRows(row)) {
  232. throw new ConstraintViolationException(
  233. "Removing old row " + Arrays.asList(row) + " violates constraint " +
  234. joiner.toFKString());
  235. }
  236. }
  237. private static void updateSecondaryValues(Joiner joiner, Object[] oldFromRow,
  238. Object[] newFromRow)
  239. throws IOException
  240. {
  241. IndexCursor toCursor = joiner.getToCursor();
  242. List<? extends Index.Column> fromCols = joiner.getColumns();
  243. List<? extends Index.Column> toCols = joiner.getToIndex().getColumns();
  244. Object[] toRow = new Object[joiner.getToTable().getColumnCount()];
  245. for(Iterator<Row> iter = joiner.findRows(oldFromRow)
  246. .setColumnNames(Collections.<String>emptySet())
  247. .iterator(); iter.hasNext(); ) {
  248. iter.next();
  249. // create update row for "to" table
  250. Arrays.fill(toRow, Column.KEEP_VALUE);
  251. for(int i = 0; i < fromCols.size(); ++i) {
  252. Object val = fromCols.get(i).getColumn().getRowValue(newFromRow);
  253. toCols.get(i).getColumn().setRowValue(toRow, val);
  254. }
  255. toCursor.updateCurrentRow(toRow);
  256. }
  257. }
  258. private static void nullSecondaryValues(Joiner joiner, Object[] oldFromRow)
  259. throws IOException
  260. {
  261. IndexCursor toCursor = joiner.getToCursor();
  262. List<? extends Index.Column> fromCols = joiner.getColumns();
  263. List<? extends Index.Column> toCols = joiner.getToIndex().getColumns();
  264. Object[] toRow = new Object[joiner.getToTable().getColumnCount()];
  265. for(Iterator<Row> iter = joiner.findRows(oldFromRow)
  266. .setColumnNames(Collections.<String>emptySet())
  267. .iterator(); iter.hasNext(); ) {
  268. iter.next();
  269. // create update row for "to" table
  270. Arrays.fill(toRow, Column.KEEP_VALUE);
  271. for(int i = 0; i < fromCols.size(); ++i) {
  272. toCols.get(i).getColumn().setRowValue(toRow, null);
  273. }
  274. toCursor.updateCurrentRow(toRow);
  275. }
  276. }
  277. private boolean anyUpdates(Object[] oldRow, Object[] newRow) {
  278. for(ColumnImpl col : _cols) {
  279. if(!MATCHER.matches(_table, col.getName(),
  280. col.getRowValue(oldRow), col.getRowValue(newRow))) {
  281. return true;
  282. }
  283. }
  284. return false;
  285. }
  286. private static boolean anyUpdates(Joiner joiner,Object[] oldRow,
  287. Object[] newRow)
  288. {
  289. Table fromTable = joiner.getFromTable();
  290. for(Index.Column iCol : joiner.getColumns()) {
  291. Column col = iCol.getColumn();
  292. if(!MATCHER.matches(fromTable, col.getName(),
  293. col.getRowValue(oldRow), col.getRowValue(newRow))) {
  294. return true;
  295. }
  296. }
  297. return false;
  298. }
  299. private static boolean areNull(Joiner joiner, Object[] row) {
  300. for(Index.Column col : joiner.getColumns()) {
  301. if(col.getColumn().getRowValue(row) != null) {
  302. return false;
  303. }
  304. }
  305. return true;
  306. }
  307. private boolean enforcing() {
  308. return _table.getDatabase().isEnforceForeignKeys();
  309. }
  310. static SharedState initSharedState() {
  311. return new SharedState();
  312. }
  313. /**
  314. * Shared state used by all FKEnforcers for a given Database.
  315. */
  316. static final class SharedState
  317. {
  318. /** current depth of cascading update calls across one or more tables */
  319. private int _updateDepth;
  320. private SharedState() {
  321. }
  322. public boolean isUpdating() {
  323. return (_updateDepth == 0);
  324. }
  325. public void pushUpdate() {
  326. ++_updateDepth;
  327. }
  328. public void popUpdate() {
  329. --_updateDepth;
  330. }
  331. }
  332. }