UniqueConstraint.cs 14 KB

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