UniqueConstraint.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. //
  2. // System.Data.UniqueConstraint.cs
  3. //
  4. // Author:
  5. // Franklin Wise <[email protected]>
  6. // Daniel Morgan <[email protected]>
  7. // Tim Coleman ([email protected])
  8. //
  9. // (C) 2002 Franklin Wise
  10. // (C) 2002 Daniel Morgan
  11. // Copyright (C) Tim Coleman, 2002
  12. //
  13. // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
  14. //
  15. // Permission is hereby granted, free of charge, to any person obtaining
  16. // a copy of this software and associated documentation files (the
  17. // "Software"), to deal in the Software without restriction, including
  18. // without limitation the rights to use, copy, modify, merge, publish,
  19. // distribute, sublicense, and/or sell copies of the Software, and to
  20. // permit persons to whom the Software is furnished to do so, subject to
  21. // the following conditions:
  22. //
  23. // The above copyright notice and this permission notice shall be
  24. // included in all copies or substantial portions of the Software.
  25. //
  26. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  27. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  28. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  29. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  30. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  31. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  32. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  33. //
  34. using System;
  35. using System.Collections;
  36. using System.ComponentModel;
  37. using System.Runtime.InteropServices;
  38. namespace System.Data {
  39. [Editor]
  40. [DefaultProperty ("ConstraintName")]
  41. [Serializable]
  42. public class UniqueConstraint : Constraint
  43. {
  44. private bool _isPrimaryKey = false;
  45. private bool __isPrimaryKey = false;
  46. private DataTable _dataTable; //set by ctor except when unique case
  47. private DataColumn [] _dataColumns;
  48. //TODO:provide helpers for this case
  49. private string [] _dataColumnNames; //unique case
  50. private bool _dataColsNotValidated;
  51. #region Constructors
  52. public UniqueConstraint (DataColumn column)
  53. {
  54. _uniqueConstraint ("", column, false);
  55. }
  56. public UniqueConstraint (DataColumn[] columns)
  57. {
  58. _uniqueConstraint ("", columns, false);
  59. }
  60. public UniqueConstraint (DataColumn column, bool isPrimaryKey)
  61. {
  62. _uniqueConstraint ("", column, isPrimaryKey);
  63. }
  64. public UniqueConstraint (DataColumn[] columns, bool isPrimaryKey)
  65. {
  66. _uniqueConstraint ("", columns, isPrimaryKey);
  67. }
  68. public UniqueConstraint (string name, DataColumn column)
  69. {
  70. _uniqueConstraint (name, column, false);
  71. }
  72. public UniqueConstraint (string name, DataColumn[] columns)
  73. {
  74. _uniqueConstraint (name, columns, false);
  75. }
  76. public UniqueConstraint (string name, DataColumn column, bool isPrimaryKey)
  77. {
  78. _uniqueConstraint (name, column, isPrimaryKey);
  79. }
  80. public UniqueConstraint (string name, DataColumn[] columns, bool isPrimaryKey)
  81. {
  82. _uniqueConstraint (name, columns, isPrimaryKey);
  83. }
  84. //Special case. Can only be added to the Collection with AddRange
  85. [Browsable (false)]
  86. public UniqueConstraint (string name, string[] columnNames, bool isPrimaryKey)
  87. {
  88. _dataColsNotValidated = true;
  89. //keep list of names to resolve later
  90. _dataColumnNames = columnNames;
  91. base.ConstraintName = name;
  92. _isPrimaryKey = isPrimaryKey;
  93. }
  94. //helper ctor
  95. private void _uniqueConstraint(string name, DataColumn column, bool isPrimaryKey)
  96. {
  97. _dataColsNotValidated = false;
  98. //validate
  99. _validateColumn (column);
  100. //Set Constraint Name
  101. base.ConstraintName = name;
  102. __isPrimaryKey = isPrimaryKey;
  103. //keep reference
  104. _dataColumns = new DataColumn [] {column};
  105. //Get table reference
  106. _dataTable = column.Table;
  107. }
  108. //helpter ctor
  109. private void _uniqueConstraint(string name, DataColumn[] columns, bool isPrimaryKey)
  110. {
  111. _dataColsNotValidated = false;
  112. //validate
  113. _validateColumns (columns, out _dataTable);
  114. //Set Constraint Name
  115. base.ConstraintName = name;
  116. //keep reference
  117. _dataColumns = columns;
  118. //PK?
  119. __isPrimaryKey = isPrimaryKey;
  120. }
  121. #endregion // Constructors
  122. #region Helpers
  123. private void _validateColumns(DataColumn [] columns)
  124. {
  125. DataTable table;
  126. _validateColumns(columns, out table);
  127. }
  128. //Validates a collection of columns with the ctor rules
  129. private void _validateColumns(DataColumn [] columns, out DataTable table) {
  130. table = null;
  131. //not null
  132. if (null == columns) throw new ArgumentNullException();
  133. //check that there is at least one column
  134. //LAMESPEC: not in spec
  135. if (columns.Length < 1)
  136. throw new InvalidConstraintException("Must be at least one column.");
  137. DataTable compareTable = columns[0].Table;
  138. //foreach
  139. foreach (DataColumn col in columns){
  140. //check individual column rules
  141. _validateColumn (col);
  142. //check that columns are all from the same table??
  143. //LAMESPEC: not in spec
  144. if (compareTable != col.Table)
  145. throw new InvalidConstraintException("Columns must be from the same table.");
  146. }
  147. table = compareTable;
  148. }
  149. //validates a column with the ctor rules
  150. private void _validateColumn(DataColumn column) {
  151. //not null
  152. if (null == column) // FIXME: This is little weird, but here it goes...
  153. throw new NullReferenceException("Object reference not set to an instance of an object.");
  154. //column must belong to a table
  155. //LAMESPEC: not in spec
  156. if (null == column.Table)
  157. throw new ArgumentException ("Column must belong to a table.");
  158. }
  159. /// <summary>
  160. /// If IsPrimaryKey is set to be true, this sets it true
  161. /// </summary>
  162. internal void UpdatePrimaryKey ()
  163. {
  164. _isPrimaryKey = __isPrimaryKey;
  165. // if unique constraint defined on single column
  166. // the column becomes unique
  167. if (_dataColumns.Length == 1){
  168. // use SetUnique - because updating Unique property causes loop
  169. _dataColumns[0].SetUnique();
  170. }
  171. }
  172. internal static void SetAsPrimaryKey(ConstraintCollection collection, UniqueConstraint newPrimaryKey)
  173. {
  174. //not null
  175. if (null == collection) throw new ArgumentNullException("ConstraintCollection can't be null.");
  176. //make sure newPrimaryKey belongs to the collection parm unless it is null
  177. if ( collection.IndexOf(newPrimaryKey) < 0 && (null != newPrimaryKey) )
  178. throw new ArgumentException("newPrimaryKey must belong to collection.");
  179. //Get existing pk
  180. UniqueConstraint uc = GetPrimaryKeyConstraint(collection);
  181. //clear existing
  182. if (null != uc) uc._isPrimaryKey = false;
  183. //set new key
  184. if (null != newPrimaryKey) newPrimaryKey._isPrimaryKey = true;
  185. }
  186. internal static UniqueConstraint GetPrimaryKeyConstraint(ConstraintCollection collection)
  187. {
  188. if (null == collection) throw new ArgumentNullException("Collection can't be null.");
  189. UniqueConstraint uc;
  190. IEnumerator enumer = collection.GetEnumerator();
  191. while (enumer.MoveNext())
  192. {
  193. uc = enumer.Current as UniqueConstraint;
  194. if (null == uc) continue;
  195. if (uc.IsPrimaryKey) return uc;
  196. }
  197. //if we got here there was no pk
  198. return null;
  199. }
  200. internal static UniqueConstraint GetUniqueConstraintForColumnSet(ConstraintCollection collection,
  201. DataColumn[] columns)
  202. {
  203. if (null == collection) throw new ArgumentNullException("Collection can't be null.");
  204. if (null == columns ) return null;
  205. UniqueConstraint uniqueConstraint;
  206. IEnumerator enumer = collection.GetEnumerator();
  207. while (enumer.MoveNext())
  208. {
  209. uniqueConstraint = enumer.Current as UniqueConstraint;
  210. if (uniqueConstraint != null)
  211. {
  212. if ( DataColumn.AreColumnSetsTheSame(uniqueConstraint.Columns, columns) )
  213. {
  214. return uniqueConstraint;
  215. }
  216. }
  217. }
  218. return null;
  219. }
  220. internal bool DataColsNotValidated {
  221. get { return (_dataColsNotValidated);
  222. }
  223. }
  224. // Helper Special Ctor
  225. // Set the _dataTable property to the table to which this instance is bound when AddRange()
  226. // is called with the special constructor.
  227. // Validate whether the named columns exist in the _dataTable
  228. internal void PostAddRange( DataTable _setTable ) {
  229. _dataTable = _setTable;
  230. DataColumn []cols = new DataColumn [_dataColumnNames.Length];
  231. int i = 0;
  232. foreach ( string _columnName in _dataColumnNames ){
  233. if ( _setTable.Columns.Contains (_columnName) ){
  234. cols [i] = _setTable.Columns [_columnName];
  235. i++;
  236. continue;
  237. }
  238. throw( new InvalidConstraintException ( "The named columns must exist in the table" ));
  239. }
  240. _dataColumns = cols;
  241. }
  242. #endregion //Helpers
  243. #region Properties
  244. [DataCategory ("Data")]
  245. [DataSysDescription ("Indicates the columns of this constraint.")]
  246. [ReadOnly (true)]
  247. public virtual DataColumn[] Columns {
  248. get { return _dataColumns; }
  249. }
  250. [DataCategory ("Data")]
  251. [DataSysDescription ("Indicates if this constraint is a primary key.")]
  252. public bool IsPrimaryKey {
  253. get { return _isPrimaryKey; }
  254. }
  255. [DataCategory ("Data")]
  256. [DataSysDescription ("Indicates the table of this constraint.")]
  257. [ReadOnly (true)]
  258. public override DataTable Table {
  259. get { return _dataTable; }
  260. }
  261. #endregion // Properties
  262. #region Methods
  263. public override bool Equals(object key2) {
  264. UniqueConstraint cst = key2 as UniqueConstraint;
  265. if (null == cst) return false;
  266. //according to spec if the cols are equal
  267. //then two UniqueConstraints are equal
  268. return DataColumn.AreColumnSetsTheSame(cst.Columns, this.Columns);
  269. }
  270. public override int GetHashCode()
  271. {
  272. //initialize hash with default value
  273. int hash = 42;
  274. int i;
  275. //derive the hash code from the columns that way
  276. //Equals and GetHashCode return Equal objects to be the
  277. //same
  278. //Get the first column hash
  279. if (this.Columns.Length > 0)
  280. hash ^= this.Columns[0].GetHashCode();
  281. //get the rest of the column hashes if there any
  282. for (i = 1; i < this.Columns.Length; i++)
  283. {
  284. hash ^= this.Columns[1].GetHashCode();
  285. }
  286. return hash ;
  287. }
  288. [MonoTODO]
  289. internal override void AddToConstraintCollectionSetup(
  290. ConstraintCollection collection)
  291. {
  292. //run Ctor rules again
  293. _validateColumns(_dataColumns);
  294. //make sure a unique constraint doesn't already exists for these columns
  295. UniqueConstraint uc = UniqueConstraint.GetUniqueConstraintForColumnSet(collection, this.Columns);
  296. if (null != uc) throw new ArgumentException("Unique constraint already exists for these" +
  297. " columns. Existing ConstraintName is " + uc.ConstraintName);
  298. //Allow only one primary key
  299. if (this.IsPrimaryKey)
  300. {
  301. uc = GetPrimaryKeyConstraint(collection);
  302. if (null != uc) uc._isPrimaryKey = false;
  303. }
  304. //FIXME: ConstraintCollection calls AssertContraint() again rigth after calling
  305. //this method, so that it is executed twice. Need to investigate which
  306. // call to remove as that migth affect other parts of the classes.
  307. AssertConstraint();
  308. }
  309. internal override void RemoveFromConstraintCollectionCleanup(
  310. ConstraintCollection collection)
  311. {
  312. Index index = this.Index;
  313. this.Index = null;
  314. // if a foreign key constraint references the same index -
  315. // change the index be to not unique.
  316. // In this case we can not just drop the index
  317. ICollection fkCollection = collection.ForeignKeyConstraints;
  318. foreach (ForeignKeyConstraint fkc in fkCollection) {
  319. if (index == fkc.Index) {
  320. fkc.Index.SetUnique (false);
  321. // this is not referencing the index anymore
  322. return;
  323. }
  324. }
  325. // if we are here no one is using this index so we can remove it.
  326. // There is no need calling drop index here
  327. // since two unique constraints never references the same index
  328. // and we already check that there is no foreign key constraint referencing it.
  329. Table.RemoveIndex (index);
  330. }
  331. [MonoTODO]
  332. internal override void AssertConstraint()
  333. {
  334. if (_dataTable == null) return; //???
  335. if (_dataColumns == null) return; //???
  336. Index fromTableIndex = null;
  337. if (Index == null) {
  338. fromTableIndex = Table.GetIndexByColumns (Columns);
  339. if (fromTableIndex == null) {
  340. Index = new Index (ConstraintName, _dataTable, _dataColumns, true);
  341. }
  342. else {
  343. fromTableIndex.SetUnique (true);
  344. Index = fromTableIndex;
  345. }
  346. }
  347. try {
  348. Table.InitializeIndex (Index);
  349. }
  350. catch (ConstraintException) {
  351. #if NET_1_1
  352. throw;
  353. #else
  354. Index = null;
  355. throw new ArgumentException (String.Format ("Column '{0}' contains non-unique values", this._dataColumns[0]));
  356. #endif
  357. }
  358. // if there is no index with same columns - add the new index to the table.
  359. if (fromTableIndex == null)
  360. Table.AddIndex (Index);
  361. }
  362. [MonoTODO]
  363. internal override void AssertConstraint(DataRow row)
  364. {
  365. if (_dataTable == null) return; //???
  366. if (_dataColumns == null) return; //???
  367. if (Index == null) {
  368. Index = Table.GetIndexByColumns (Columns, true);
  369. if (Index == null) {
  370. Index = new Index (ConstraintName, _dataTable, _dataColumns, true);
  371. Table.AddIndex (Index);
  372. }
  373. }
  374. object val;
  375. for (int i = 0; i < _dataColumns.Length; i++) {
  376. val = row[_dataColumns[i]];
  377. if (val == null || val == DBNull.Value)
  378. throw new NoNullAllowedException("Column '" + _dataColumns[i].ColumnName + "' does not allow nulls.");
  379. }
  380. try {
  381. UpdateIndex (row);
  382. }
  383. catch (ConstraintException) {
  384. throw new ConstraintException(GetErrorMessage(row));
  385. }
  386. }
  387. private string GetErrorMessage(DataRow row)
  388. {
  389. int i;
  390. System.Text.StringBuilder sb = new System.Text.StringBuilder(row[_dataColumns[0]].ToString());
  391. for (i = 1; i < _dataColumns.Length; i++)
  392. sb = sb.Append(", ").Append(row[_dataColumns[i].ColumnName]);
  393. string valStr = sb.ToString();
  394. sb = new System.Text.StringBuilder(_dataColumns[0].ColumnName);
  395. for (i = 1; i < _dataColumns.Length; i++)
  396. sb = sb.Append(", ").Append(_dataColumns[i].ColumnName);
  397. string colStr = sb.ToString();
  398. return "Column '" + colStr + "' is constrained to be unique. Value '" + valStr + "' is already present.";
  399. }
  400. #endregion // Methods
  401. }
  402. }