2004-03-29 Umadevi S (sumadevi@novell.com)
[mono.git] / mcs / class / System.Data / System.Data / DataColumn.cs
1 //
2 // System.Data.DataColumn.cs
3 //
4 // Author:
5 //   Franklin Wise (gracenote@earthlink.net)
6 //   Christopher Podurgiel (cpodurgiel@msn.com)
7 //   Rodrigo Moya (rodrigo@ximian.com)
8 //   Daniel Morgan (danmorg@sc.rr.com)
9 //   Tim Coleman (tim@timcoleman.com)
10 //
11 // (C) Copyright 2002, Franklin Wise
12 // (C) Chris Podurgiel
13 // (C) Ximian, Inc 2002
14 // Copyright (C) Tim Coleman, 2002
15 // Copyright (C) Daniel Morgan, 2002, 2003
16 //
17
18 using System;
19 using System.ComponentModel;
20 using System.Reflection;
21 using System.Collections;
22 using System.Data.Common;
23 using Mono.Data.SqlExpressions;
24
25 namespace System.Data {
26         internal delegate void DelegateColumnValueChange(DataColumn column, DataRow row, object proposedValue);
27         
28         /// <summary>
29         /// Summary description for DataColumn.
30         /// </summary>
31
32         [Editor]
33         [ToolboxItem (false)]
34         [DefaultMember ("Item")]
35         [DefaultProperty ("ColumnName")]
36         [DesignTimeVisible (false)]
37         [TypeConverterAttribute (typeof (ComponentConverter))]
38         public class DataColumn : MarshalByValueComponent
39         {               
40                 #region Events
41                 [MonoTODO]
42                 //used for constraint validation
43                 //if an exception is fired during this event the change should be canceled
44                 internal event DelegateColumnValueChange ValidateColumnValueChange;
45
46                 //used for FK Constraint Cascading rules
47                 internal event DelegateColumnValueChange ColumnValueChanging;
48                 #endregion //Events
49                 
50                 #region Fields
51
52                 private bool _allowDBNull = true;
53                 private bool _autoIncrement;
54                 private long _autoIncrementSeed;
55                 private long _autoIncrementStep = 1;
56                 private long _nextAutoIncrementValue;
57                 private bool dataHasBeenSet;
58                 private string _caption;
59                 private MappingType _columnMapping;
60                 private string _columnName;
61                 private Type _dataType;
62                 private object _defaultValue = DBNull.Value;
63                 private string expression;
64                 private IExpression compiledExpression;
65                 private PropertyCollection _extendedProperties = new PropertyCollection ();
66                 private int maxLength = -1; //-1 represents no length limit
67                 private string nameSpace = "";
68                 private int _ordinal = -1; //-1 represents not part of a collection
69                 private string prefix = "";
70                 private bool readOnly;
71                 private DataTable _table;
72                 private bool unique;
73
74                 #endregion // Fields
75
76                 #region Constructors
77
78                 public DataColumn() : this("", typeof (string), "", MappingType.Element)
79                 {
80                 }
81
82                 //TODO: Ctor init vars directly
83                 public DataColumn(string columnName): this(columnName, typeof (string), "", MappingType.Element)
84                 {
85                 }
86
87                 public DataColumn(string columnName, Type dataType): this(columnName, dataType, "", MappingType.Element)
88                 {
89                 }
90
91                 public DataColumn( string columnName, Type dataType, 
92                         string expr): this(columnName, dataType, expr, MappingType.Element)
93                 {
94                 }
95
96                 public DataColumn(string columnName, Type dataType, 
97                         string expr, MappingType type)
98                 {
99                         ColumnName = (columnName == null ? "" : columnName);
100                         
101                         if(dataType == null) {
102                                 throw new ArgumentNullException("dataType can't be null.");
103                         }
104                         
105                         DataType = dataType;
106                         Expression = expr == null ? "" : expr;
107                         ColumnMapping = type;
108                 }
109                 #endregion
110
111                 #region Properties
112
113                 [DataCategory ("Data")]
114                 [DataSysDescription ("Indicates whether null values are allowed in this column.")]
115                 [DefaultValue (true)]
116                 public bool AllowDBNull
117                 {
118                         get {
119                                 return _allowDBNull;
120                         }
121                         set {
122                                 //TODO: If we are a part of the table and this value changes
123                                 //we need to validate that all the existing values conform to the new setting
124
125                                 if (true == value)
126                                 {
127                                         _allowDBNull = true;
128                                         return;
129                                 }
130                                 
131                                 //if Value == false case
132                                 if (null != _table)
133                                 {
134                                         if (_table.Rows.Count > 0)
135                                         {
136                                                 bool nullsFound = false;
137                                                 for(int r = 0; r < _table.Rows.Count; r++) {
138                                                         DataRow row = _table.Rows[r];
139                                                         if(row.IsNull(this)) {
140                                                                 nullsFound = true;
141                                                                 break;
142                                                         }
143                                                 }
144                                                 
145                                                 if (nullsFound)
146                                                         throw new DataException("Column '" + ColumnName + "' has null values in it.");
147                                                 //TODO: Validate no null values exist
148                                                 //do we also check different versions of the row??
149                                         }
150                                 }
151                                         
152                                 _allowDBNull = value;
153                         }
154                 }
155         
156                 /// <summary>
157                 /// Gets or sets a value indicating whether the column automatically increments the value of the column for new rows added to the table.
158                 /// </summary>
159                 /// <remarks>
160                 ///             If the type of this column is not Int16, Int32, or Int64 when this property is set, 
161                 ///             the DataType property is coerced to Int32. An exception is generated if this is a computed column 
162                 ///             (that is, the Expression property is set.) The incremented value is used only if the row's value for this column, 
163                 ///             when added to the columns collection, is equal to the default value.
164                 ///     </remarks>
165                 [DataCategory ("Data")]
166                 [DataSysDescription ("Indicates whether the column automatically increments itself for new rows added to the table.  The type of this column must be Int16, Int32, or Int64.")]
167                 [DefaultValue (false)]
168                 [RefreshProperties (RefreshProperties.All)]
169                 public bool AutoIncrement
170                 {
171                         get {
172                                 return _autoIncrement;
173                         }
174                         set {
175                                 if(value == true)
176                                 {
177                                         //Can't be true if this is a computed column
178                                         if (Expression != string.Empty)
179                                         {
180                                                 throw new ArgumentException("Can not Auto Increment a computed column."); 
181                                         }
182
183                                         //If the DataType of this Column isn't an Int
184                                         //Make it an int
185                                         TypeCode typeCode = Type.GetTypeCode(_dataType);
186                                         if(typeCode != TypeCode.Int16 && 
187                                            typeCode != TypeCode.Int32 && 
188                                            typeCode != TypeCode.Int64)
189                                         {
190                                                 _dataType = typeof(Int32); 
191                                         }
192                                 }
193                                 _autoIncrement = value;
194                         }
195                 }
196
197                 [DataCategory ("Data")]
198                 [DataSysDescription ("Indicates the starting value for an AutoIncrement column.")]
199                 [DefaultValue (0)]
200                 public long AutoIncrementSeed
201                 {
202                         get {
203                                 return _autoIncrementSeed;
204                         }
205                         set {
206                                 _autoIncrementSeed = value;
207                                 _nextAutoIncrementValue = _autoIncrementSeed;
208                         }
209                 }
210
211                 [DataCategory ("Data")]
212                 [DataSysDescription ("Indicates the increment used by an AutoIncrement column.")]
213                 [DefaultValue (1)]
214                 public long AutoIncrementStep
215                 {
216                         get {
217                                 return _autoIncrementStep;
218                         }
219                         set {
220                                 _autoIncrementStep = value;
221                         }
222                 }
223
224                 internal void UpdateAutoIncrementValue (long value) 
225                 {
226                         if(value > _nextAutoIncrementValue) {
227                                 _nextAutoIncrementValue = value;
228                                 AutoIncrementValue ();
229                         }
230                 }
231
232                 internal long AutoIncrementValue () 
233                 {
234                         long currentValue = _nextAutoIncrementValue;
235                         _nextAutoIncrementValue += AutoIncrementStep;
236                         return currentValue;
237                 }
238
239                 internal long GetAutoIncrementValue ()
240                 {
241                         return _nextAutoIncrementValue;
242                 }
243
244                 internal bool DataHasBeenSet {
245                         get {
246                                 return dataHasBeenSet;
247                         }
248                         set {
249                                 dataHasBeenSet = value;
250                         }
251                 }
252
253                 [DataCategory ("Data")]
254                 [DataSysDescription ("Indicates the default user-interface caption for this column.")]
255                 public string Caption 
256                 {
257                         get {
258                                 if(_caption == null)
259                                         return ColumnName;
260                                 else
261                                         return _caption;
262                         }
263                         set {
264                                 _caption = value;
265                         }
266                 }
267                 [DataSysDescription ("Indicates how this column persists in XML: as an attribute, element, simple content node, or nothing.")]
268                 [DefaultValue (MappingType.Element)]
269                 public virtual MappingType ColumnMapping
270                 {
271                         get {
272                                 return _columnMapping;
273                         }
274                         set {
275                                 _columnMapping = value;
276                         }
277                 }
278
279                 [DataCategory ("Data")]
280                 [DataSysDescription ("Indicates the name used to look up this column in the Columns collection of a DataTable.")]
281                 [RefreshProperties (RefreshProperties.All)]
282                 [DefaultValue ("")]
283                 public string ColumnName
284                 {
285                         get {
286                                 return "" + _columnName;
287                         }
288                         set {
289                                 //Both are checked after the column is part of the collection
290                                 //TODO: Check Name duplicate
291                                 //TODO: check Name != null
292                                 _columnName = value;
293                         }
294                 }
295
296                 [DataCategory ("Data")]
297                 [DataSysDescription ("Indicates the type of data stored in this column.")]
298                 [DefaultValue (typeof (string))]
299                 [RefreshProperties (RefreshProperties.All)]
300                 [TypeConverterAttribute (typeof (ColumnTypeConverter))] 
301                 public Type DataType
302                 {
303                         get {
304                                 return _dataType;
305                         }
306                         set {
307                                 // check if data already exists can we change the datatype
308                                 if(DataHasBeenSet == true)
309                                         throw new ArgumentException("The column already has data stored.");
310
311                                 // we want to check that the datatype is supported?
312                                 TypeCode typeCode = Type.GetTypeCode(value);
313                                 
314                                 //Check AutoIncrement status, make compatible datatype
315                                 if(AutoIncrement == true) {
316                                         if(typeCode != TypeCode.Int16 &&
317                                            typeCode != TypeCode.Int32 &&
318                                            typeCode != TypeCode.Int64)
319                                                 AutoIncrement = false;
320                                 }
321                                 _dataType = value;
322                         }
323                 }
324
325                 /// <summary>
326                 /// 
327                 /// </summary>
328                 /// <remarks>When AutoIncrement is set to true, there can be no default value.</remarks>
329                 /// <exception cref="System.InvalidCastException"></exception>
330                 /// <exception cref="System.ArgumentException"></exception>
331                 [DataCategory ("Data")]
332                 [DataSysDescription ("Indicates the default column value used when adding new rows to the table.")]
333                 [TypeConverterAttribute (typeof (System.Data.DefaultValueTypeConverter))]
334                 public object DefaultValue
335                 {
336                         get {
337                                 return _defaultValue;
338                         }
339                         set {
340                                 object tmpObj;
341                                 if ((this._defaultValue == null) || (!this._defaultValue.Equals(value)))
342                                 {
343                                         //If autoIncrement == true throw
344                                         if (AutoIncrement) 
345                                         {
346                                                 throw new ArgumentException("Can not set default value while" +
347                                                         " AutoIncrement is true on this column.");
348                                         }
349
350                                         if (value == null) 
351                                         {
352                                                 tmpObj = DBNull.Value;
353                                         }
354                                         else
355                                                 tmpObj = value;
356
357                                         if ((this.DataType != typeof (object))&& (tmpObj != DBNull.Value))
358                                         {
359                                                 try
360                                                 {
361                                                         //Casting to the new type
362                                                         tmpObj= Convert.ChangeType(tmpObj,this.DataType);
363                                                 }
364                                                 catch (InvalidCastException)
365                                                 {
366                                                         throw new InvalidCastException("Default Value type is not compatible with" + 
367                                                                 " column type.");
368                                                 }
369                                         }
370                                         _defaultValue = tmpObj;
371                                 }
372                         }
373                 }
374
375                 [DataCategory ("Data")]
376                 [DataSysDescription ("Indicates the value that this column computes for each row based on other columns instead of taking user input.")]
377                 [DefaultValue ("")]
378                 [RefreshProperties (RefreshProperties.All)]
379                 public string Expression
380                 {
381                         get {
382                                 return expression;
383                         }
384                         set {
385                                 if (value == null)
386                                         value = String.Empty;
387                                         
388                                 if (value != String.Empty) {
389                                         Parser parser = new Parser ();
390                                         compiledExpression = parser.Compile (value);
391                                         expression = value;  
392
393                                         ReadOnly = true;
394                         } 
395                         }
396                 }
397
398                 [Browsable (false)]
399                 [DataCategory ("Data")]
400                 [DataSysDescription ("The collection that holds custom user information.")]
401                 public PropertyCollection ExtendedProperties
402                 {
403                         get {
404                                 return _extendedProperties;
405                         }
406                 }
407
408                 [DataCategory ("Data")]
409                 [DataSysDescription ("Indicates the maximum length of the value this column allows.")]
410                 [DefaultValue (-1)]
411                 public int MaxLength
412                 {
413                         get {
414                                 //Default == -1 no max length
415                                 return maxLength;
416                         }
417                         set {
418                                 //only applies to string columns
419                                 maxLength = value;
420                         }
421                 }
422
423                 [DataCategory ("Data")]
424                 [DataSysDescription ("Indicates the XML uri for elements stored in this  column.")]
425                 public string Namespace
426                 {
427                         get {
428                                 return nameSpace;
429                         }
430                         set {
431                                 nameSpace = value;
432                         }
433                 }
434
435                 //Need a good way to set the Ordinal when the column is added to a columnCollection.
436                 [Browsable (false)]
437                 [DataCategory ("Data")]
438                 [DataSysDescription ("Indicates the index of this column in the Columns collection.")]
439                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
440                 public int Ordinal
441                 {
442                         get {
443                                 //value is -1 if not part of a collection
444                                 return _ordinal;
445                         }
446                 }
447
448                 internal void SetOrdinal(int ordinal)
449                 {
450                         _ordinal = ordinal;
451                 }
452
453                 [DataCategory ("Data")]
454                 [DataSysDescription ("Indicates the prefix used for this DataColumn in the xml representation.")]
455                 [DefaultValue ("")]
456                 public string Prefix
457                 {
458                         get {
459                                 return prefix;
460                         }
461                         set {
462                                 prefix = value;
463                         }
464                 }
465
466                 [DataCategory ("Data")]
467                 [DataSysDescription ("Indicates whether this column allows changes once a row has been added to the table.")]
468                 [DefaultValue (false)]
469                 public bool ReadOnly
470                 {
471                         get {
472                                 return readOnly;
473                         }
474                         set {
475                                 readOnly = value;
476                         }
477                 }
478
479                 [Browsable (false)]
480                 [DataCategory ("Data")]
481                 [DataSysDescription ("Returns the DataTable to which this column belongs.")]
482                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]      
483                 public DataTable Table
484                 {
485                         get {
486                                 return _table;
487                         }
488                 }
489
490                 [MonoTODO]
491                 [DataCategory ("Data")]
492                 [DataSysDescription ("Indicates whether this column should restrict its values in the rows of the table to be unique.")]
493                 [DefaultValue (false)]
494                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
495                 public bool Unique 
496                 {
497                         get {
498                                 return unique;
499                         }
500                         set {
501                                 //if Table == null then the UniqueConstraint is
502                                 //created on addition to the collection
503                                 
504                                 //FIXME?: need to check if value is the same
505                                 //because when calling "new UniqueConstraint"
506                                 //the new object tries to set "column.Unique = True"
507                                 //which creates an infinite loop.
508                                 if(unique != value)
509                                 {
510                                 unique = value;
511
512                                         if( value )
513                                         {
514                                                 if (Expression != null && Expression != "")
515                                                         throw new ArgumentException("Cannot change Unique property for the expression column.");
516                                                 if( _table != null )
517                                                 {
518                                                         UniqueConstraint uc = new UniqueConstraint(this);
519                                                         _table.Constraints.Add(uc);
520                                                 }
521                                         }
522                                         else
523                                         {
524                                                 if( _table != null )
525                                                 {
526                                                         ConstraintCollection cc = _table.Constraints;
527                                                         //foreach (Constraint c in cc) 
528                                                         for (int i = 0; i < cc.Count; i++)
529                                                         {
530                                                                 Constraint c = cc[i];
531                                                                 if (c is UniqueConstraint)
532                                                                 {
533                                                                         DataColumn[] cols = ((UniqueConstraint)c).Columns;
534                                                                         
535                                                                         if (cols.Length == 1 && cols[0] == this)
536                                                                         {
537                                                                                 if (!cc.CanRemove(c))
538                                                                                         throw new ArgumentException("Cannot remove unique constraint '" + c.ConstraintName + "'. Remove foreign key constraint first.");
539
540                                                                                 cc.Remove(c);
541                                                                         }
542                                                                         
543                                                                 }
544                                                         }
545                                                 }
546                                         }
547
548                                 }
549                         }
550                 }
551
552                 #endregion // Properties
553
554                 #region Methods
555                 
556 /* ??
557                 [MonoTODO]
558                 protected internal void CheckNotAllowNull() {
559                 }
560
561                 [MonoTODO]
562                 protected void CheckUnique() {
563                 }
564 */
565
566                 /// <summary>
567                 ///  Sets unique true whithout creating Constraint
568                 /// </summary>
569                 internal void SetUnique() 
570                 {
571                         unique = true;
572                 }
573
574
575                 [MonoTODO]
576                 internal void AssertCanAddToCollection()
577                 {
578                         //Check if Default Value is set and AutoInc is set
579                 }
580                 
581                 [MonoTODO]
582                 protected internal virtual void 
583                 OnPropertyChanging (PropertyChangedEventArgs pcevent) {
584                 }
585
586                 [MonoTODO]
587                 protected internal void RaisePropertyChanging(string name) {
588                 }
589
590                 /// <summary>
591                 /// Gets the Expression of the column, if one exists.
592                 /// </summary>
593                 /// <returns>The Expression value, if the property is set; 
594                 /// otherwise, the ColumnName property.</returns>
595                 public override string ToString()
596                 {
597                         if (expression != string.Empty)
598                                 return ColumnName + " + " + expression;
599                         
600                         return ColumnName;
601                 }
602
603                 [MonoTODO]
604                 internal void SetTable(DataTable table) {
605                         _table = table; 
606                         // this will get called by DataTable 
607                         // and DataColumnCollection
608                 }
609
610                 
611                 // Returns true if all the same collumns are in columnSet and compareSet
612                 internal static bool AreColumnSetsTheSame(DataColumn[] columnSet, DataColumn[] compareSet)
613                 {
614                         if (null == columnSet && null == compareSet) return true;
615                         if (null == columnSet || null == compareSet) return false;
616
617                         if (columnSet.Length != compareSet.Length) return false;
618                         
619                         foreach (DataColumn col in columnSet)
620                         {
621                                 bool matchFound = false;
622                                 foreach (DataColumn compare in compareSet)
623                                 {
624                                         if (col == compare)
625                                         {
626                                                 matchFound = true;                                      
627                                         }
628                                 }
629                                 if (! matchFound) return false;
630                         }
631                         
632                         return true;
633                 }
634                 
635                 static internal int CompareValues (object val1, object val2, Type t, bool ignoreCase)
636                 {
637                         IComparer comparer = DBComparerFactory.GetComparer (t, ignoreCase);
638                         return comparer.Compare (val1, val2);
639                 }
640
641                 #endregion // Methods
642
643         }
644 }