Welcome to mirror list, hosted at ThFree Co, Russian Federation.

UniqueConstraint.cs « System.Data « System.Data « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: fb7c88b34ba6c1ca1b5a66d5f887cf9cdf16e13d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
//
// System.Data.UniqueConstraint.cs
//
// Author:
//   Franklin Wise <gracenote@earthlink.net>
//   Daniel Morgan <danmorg@sc.rr.com>
//   Tim Coleman (tim@timcoleman.com)
//   
// (C) 2002 Franklin Wise
// (C) 2002 Daniel Morgan
// Copyright (C) Tim Coleman, 2002

//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Data.Common;

namespace System.Data {
	[Editor ("Microsoft.VSDesigner.Data.Design.UniqueConstraintEditor, " + Consts.AssemblyMicrosoft_VSDesigner,
		 "System.Drawing.Design.UITypeEditor, " + Consts.AssemblySystem_Drawing)]
	[DefaultProperty ("ConstraintName")]
	[Serializable]
	public class UniqueConstraint : Constraint 
	{
		private bool _isPrimaryKey = false;
		private bool _belongsToCollection = false;
		private DataTable _dataTable; //set by ctor except when unique case
		
		//FIXME: create a class which will wrap this collection
		private DataColumn [] _dataColumns;

		//TODO:provide helpers for this case
		private string [] _dataColumnNames; //unique case
		private bool _dataColsNotValidated;
		private ForeignKeyConstraint _childConstraint = null;

		#region Constructors

		public UniqueConstraint (DataColumn column) 
		{
			_uniqueConstraint ("", column, false);
		}

		public UniqueConstraint (DataColumn[] columns) 
		{
			_uniqueConstraint ("", columns, false);
		}

		public UniqueConstraint (DataColumn column, bool isPrimaryKey) 
		{
			_uniqueConstraint ("", column, isPrimaryKey);
		}

		public UniqueConstraint (DataColumn[] columns, bool isPrimaryKey) 
		{
			_uniqueConstraint ("", columns, isPrimaryKey);
		}

		public UniqueConstraint (string name, DataColumn column) 
		{
			_uniqueConstraint (name, column, false);
		}

		public UniqueConstraint (string name, DataColumn[] columns) 
		{
			_uniqueConstraint (name, columns, false);
		}

		public UniqueConstraint (string name, DataColumn column, bool isPrimaryKey) 
		{
			_uniqueConstraint (name, column, isPrimaryKey);
		}

		public UniqueConstraint (string name, DataColumn[] columns, bool isPrimaryKey) 
		{
			_uniqueConstraint (name, columns, isPrimaryKey);
		}

		//Special case.  Can only be added to the Collection with AddRange
		[Browsable (false)]
		public UniqueConstraint (string name, string[] columnNames, bool isPrimaryKey) 
		{
			 _dataColsNotValidated = true;
                                                                                                    
            //keep list of names to resolve later
            _dataColumnNames = columnNames;
                                                                                        
            base.ConstraintName = name;
                                                                                        
            _isPrimaryKey = isPrimaryKey;

		}

		//helper ctor
		private void _uniqueConstraint(string name, DataColumn column, bool isPrimaryKey) 
		{
			_dataColsNotValidated = false;
			//validate
			_validateColumn (column);

			//Set Constraint Name
			base.ConstraintName = name;

			_isPrimaryKey = isPrimaryKey;

			//keep reference 
			_dataColumns = new DataColumn [] {column};
			
			//Get table reference
			_dataTable = column.Table;			
		}

		//helpter ctor	
		private void _uniqueConstraint(string name, DataColumn[] columns, bool isPrimaryKey) 
		{
			_dataColsNotValidated = false;
			
			//validate
			_validateColumns (columns, out _dataTable);

			//Set Constraint Name
			base.ConstraintName = name;

			//keep reference
			_dataColumns = columns;

			//PK?
			_isPrimaryKey = isPrimaryKey;			
		}
		
		#endregion // Constructors

		#region Helpers
		
		private void _validateColumns(DataColumn [] columns)
		{
			DataTable table;
			_validateColumns(columns, out table);
		}
		
		//Validates a collection of columns with the ctor rules
		private void _validateColumns(DataColumn [] columns, out DataTable table) {
			table = null;

			//not null
			if (null == columns) throw new ArgumentNullException();
			
			//check that there is at least one column
			//LAMESPEC: not in spec
			if (columns.Length < 1)
				throw new InvalidConstraintException("Must be at least one column.");
			
			DataTable compareTable = columns[0].Table;
			//foreach
			foreach (DataColumn col in columns){
				
				//check individual column rules
				_validateColumn (col);
				
				
				//check that columns are all from the same table??
				//LAMESPEC: not in spec
				if (compareTable != col.Table)
					throw new InvalidConstraintException("Columns must be from the same table.");
				
			}

			table = compareTable;
		}
		
		//validates a column with the ctor rules
		private void _validateColumn(DataColumn column) {
	
			//not null
			if (null == column)  // FIXME: This is little weird, but here it goes...
				throw new NullReferenceException("Object reference not set to an instance of an object.");

			
			//column must belong to a table
			//LAMESPEC: not in spec
			if (null == column.Table)
				throw new ArgumentException ("Column must belong to a table.");			
		}

		internal static void SetAsPrimaryKey(ConstraintCollection collection, UniqueConstraint newPrimaryKey)
		{
			//not null
			if (null == collection) throw new ArgumentNullException("ConstraintCollection can't be null.");
			
			//make sure newPrimaryKey belongs to the collection parm unless it is null
			if (  collection.IndexOf(newPrimaryKey) < 0 && (null != newPrimaryKey) ) 
				throw new ArgumentException("newPrimaryKey must belong to collection.");
			
			//Get existing pk
			UniqueConstraint uc = GetPrimaryKeyConstraint(collection);
			
			//clear existing
			if (null != uc) uc._isPrimaryKey = false;

			//set new key
			if (null != newPrimaryKey) newPrimaryKey._isPrimaryKey = true;
			
			
		}

		internal static UniqueConstraint GetPrimaryKeyConstraint(ConstraintCollection collection)
		{
			if (null == collection) throw new ArgumentNullException("Collection can't be null.");

			UniqueConstraint uc;
			IEnumerator enumer = collection.GetEnumerator();
			while (enumer.MoveNext())
			{
				uc = enumer.Current as UniqueConstraint;
				if (null == uc) continue;
				
				if (uc.IsPrimaryKey) return uc;	
			}

			//if we got here there was no pk
			return null;
			
		}

		internal static UniqueConstraint GetUniqueConstraintForColumnSet(ConstraintCollection collection,
				DataColumn[] columns)
		{
			if (null == collection) throw new ArgumentNullException("Collection can't be null.");
			if (null == columns ) return null;
			
			foreach(Constraint constraint in collection) {
				if (constraint is UniqueConstraint) {
					UniqueConstraint uc = constraint as UniqueConstraint;
					if ( DataColumn.AreColumnSetsTheSame(uc.Columns, columns) ) {
						return uc;
					}
				}
			}
			return null;
		}

		internal bool DataColsNotValidated 
		{               
			get { 
				return (_dataColsNotValidated); 
			}
		 }


		internal ForeignKeyConstraint ChildConstraint {
			get { return _childConstraint; }
			set { _childConstraint = value; }
		}

		// Helper Special Ctor
		// Set the _dataTable property to the table to which this instance is bound when AddRange()
		// is called with the special constructor.
		// Validate whether the named columns exist in the _dataTable
		internal void PostAddRange(DataTable _setTable) 
		{                
			_dataTable = _setTable;
			if (_isPrimaryKey == true && _setTable.PrimaryKey.Length != 0)
				throw new ArgumentException ("Cannot add primary key constraint since primary key" +
						"is already set for the table");

			DataColumn[] cols = new DataColumn [_dataColumnNames.Length];
			int i = 0;

			foreach (string _columnName in _dataColumnNames) {
				if (_setTable.Columns.Contains (_columnName)) {
					cols [i] = _setTable.Columns [_columnName];
					i++;
					continue;
				}
				throw(new InvalidConstraintException ("The named columns must exist in the table"));
			}
			_dataColumns = cols;
		}


		#endregion //Helpers

		#region Properties

		[DataCategory ("Data")]
		[DataSysDescription ("Indicates the columns of this constraint.")]
		[ReadOnly (true)]
		public virtual DataColumn[] Columns {
			get { return _dataColumns; }
		}

		[DataCategory ("Data")]
		[DataSysDescription ("Indicates if this constraint is a primary key.")]
		public bool IsPrimaryKey {
			get { 
				if (Table == null || (!_belongsToCollection)) {
					return false;
				}
				return _isPrimaryKey; 
			}
		}

		[DataCategory ("Data")]
		[DataSysDescription ("Indicates the table of this constraint.")]
		[ReadOnly (true)]
		public override DataTable Table {
			get { return _dataTable; }
		}

		#endregion // Properties

		#region Methods

		public override bool Equals(object key2) {

			UniqueConstraint cst = key2 as UniqueConstraint;
			if (null == cst) return false;

			//according to spec if the cols are equal
			//then two UniqueConstraints are equal
			return DataColumn.AreColumnSetsTheSame(cst.Columns, this.Columns);	

		}

		public override int GetHashCode() 
		{
			//initialize hash with default value 
			int hash = 42;
			int i;

			//derive the hash code from the columns that way
			//Equals and GetHashCode return Equal objects to be the
			//same

			//Get the first column hash
			if (this.Columns.Length > 0)
				hash ^= this.Columns[0].GetHashCode();
			
			//get the rest of the column hashes if there any
			for (i = 1; i < this.Columns.Length; i++)
			{
				hash ^= this.Columns[1].GetHashCode();
				
			}
			
			return hash ;
		}
		
		internal override void AddToConstraintCollectionSetup(
				ConstraintCollection collection)
		{
			for (int i = 0; i < Columns.Length; i++)
				if (Columns[i].Table != collection.Table)
					throw new ArgumentException("These columns don't point to this table.");
			//run Ctor rules again
			_validateColumns(_dataColumns);
			
			//make sure a unique constraint doesn't already exists for these columns
			UniqueConstraint uc = UniqueConstraint.GetUniqueConstraintForColumnSet(collection, this.Columns);	
			if (null != uc) throw new ArgumentException("Unique constraint already exists for these" +
					" columns. Existing ConstraintName is " + uc.ConstraintName);

			//Allow only one primary key
			if (this.IsPrimaryKey) {
				uc = GetPrimaryKeyConstraint(collection);
				if (null != uc) uc._isPrimaryKey = false;
			}

			// if constraint is based on one column only
			// this column becomes unique
			if (_dataColumns.Length == 1) {
				_dataColumns[0].SetUnique();
			}
					
			//FIXME: ConstraintCollection calls AssertContraint() again rigth after calling
			//this method, so that it is executed twice. Need to investigate which
			// call to remove as that migth affect other parts of the classes.
			//AssertConstraint();
			if (IsConstraintViolated())
				throw new ArgumentException("These columns don't currently have unique values.");

			_belongsToCollection = true;
		}
					
		
		internal override void RemoveFromConstraintCollectionCleanup( 
				ConstraintCollection collection)
		{
			_belongsToCollection = false;
			Index index = Index;
			Index = null;
		}

		internal override bool IsConstraintViolated()
		{	
			if (Index == null) {
				Index = Table.GetIndex(Columns,null,DataViewRowState.None,null,false);
			}

			if (Index.HasDuplicates) {
				int[] dups = Index.Duplicates;
				for (int i = 0; i < dups.Length; i++){
					DataRow row = Table.RecordCache[dups[i]];
					ArrayList columns = new ArrayList();
					ArrayList values = new ArrayList();
					foreach (DataColumn col in Columns){
						columns.Add(col.ColumnName);
						values.Add(row[col].ToString());
					}

					string columnNames = String.Join(",", (string[])columns.ToArray(typeof(string)));
					string columnValues = String.Join(",", (string[])values.ToArray(typeof(string)));

					row.RowError = String.Format("Column(s) '{0}' are constrained to be unique.  Value(s) '{1}' are already present", columnNames, columnValues);
				}
				// FIXME : check the exception to be thrown here
				// throw new ConstraintException("These columns don't currently have unique values");
				//throw new ConstraintException ("Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.");
				return true;
			}

			return false;
		}

		internal override void AssertConstraint(DataRow row)
		{	
			if (IsPrimaryKey && row.HasVersion(DataRowVersion.Default)) {
				for (int i = 0; i < Columns.Length; i++) {
					if (row.IsNull(Columns[i])) {
						throw new NoNullAllowedException("Column '" + Columns[i].ColumnName + "' does not allow nulls.");
					}
				}
			}
			
			if (Index == null) {
				Index = Table.GetIndex(Columns,null,DataViewRowState.None,null,false);
			}

			if (Index.HasDuplicates) {
				throw new ConstraintException(GetErrorMessage(row));
			}
		}

		internal override bool IsColumnContained(DataColumn column)
		{
			for (int i = 0; i < _dataColumns.Length; i++)
				if (column == _dataColumns[i])
					return true;

			return false;
		}

		internal override bool CanRemoveFromCollection(ConstraintCollection col, bool shouldThrow){
			if (Equals(col.Table.PrimaryKey)){
				if (shouldThrow)
					throw new ArgumentException("Cannot remove unique constraint since it's the primary key of a table.");

				return false;
			}
			
			if (Table.DataSet == null)
				return true;

			if (ChildConstraint != null) {
				if (!shouldThrow)
					return false;
				throw new ArgumentException (String.Format (
								"Cannot remove unique constraint '{0}'." +
								"Remove foreign key constraint '{1}' first.",
								ConstraintName,ChildConstraint.ConstraintName));
			}
			return true;
		}

		private string GetErrorMessage(DataRow row)
		{
			int i;
			 
			System.Text.StringBuilder sb = new System.Text.StringBuilder(row[_dataColumns[0]].ToString());
			for (i = 1; i < _dataColumns.Length; i++) {
				sb = sb.Append(", ").Append(row[_dataColumns[i].ColumnName]);
			}
			string valStr = sb.ToString();
			sb = new System.Text.StringBuilder(_dataColumns[0].ColumnName);
			for (i = 1; i < _dataColumns.Length; i++) {
				sb = sb.Append(", ").Append(_dataColumns[i].ColumnName);
			}
			string colStr = sb.ToString();
			return "Column '" + colStr + "' is constrained to be unique.  Value '" + valStr + "' is already present.";
		}
			               
		
		#endregion // Methods

	}

	
}