DataRowCollection.cs (InsertAt): Add a check for null row. Replace check of IndexOf...
[mono.git] / mcs / class / System.Data / System.Data / DataRowCollection.cs
1 //
2 // System.Data.DataRowCollection.cs
3 //
4 // Author:
5 //   Daniel Morgan <danmorg@sc.rr.com>
6 //   Tim Coleman <tim@timcoleman.com>
7 //
8 // (C) Ximian, Inc 2002
9 // (C) Copyright 2002 Tim Coleman
10 // (C) Copyright 2002 Daniel Morgan
11 //
12
13 using System;
14 using System.Collections;
15 using System.ComponentModel;
16
17 namespace System.Data
18 {
19         /// <summary>
20         /// Collection of DataRows in a DataTable
21         /// </summary>
22         [Serializable]
23         public class DataRowCollection : InternalDataCollectionBase 
24         {
25                 private DataTable table;
26
27                 /// <summary>
28                 /// Internal constructor used to build a DataRowCollection.
29                 /// </summary>
30                 internal DataRowCollection (DataTable table) : base ()
31                 {
32                         this.table = table;
33                 }
34
35                 /// <summary>
36                 /// Gets the row at the specified index.
37                 /// </summary>
38                 public DataRow this[int index] 
39                 {
40                         get { 
41                                 if (index >= Count)
42                                         throw new IndexOutOfRangeException ("There is no row at position " + index + ".");
43
44                                 return (DataRow) list[index]; 
45                         }
46                 }
47
48                 /// <summary>
49                 /// This member overrides InternalDataCollectionBase.List
50                 /// </summary>
51                 protected override ArrayList List 
52                 {
53                         get { return list; }
54                 }               
55
56                 /// <summary>
57                 /// Adds the specified DataRow to the DataRowCollection object.
58                 /// </summary>
59                 public void Add (DataRow row) 
60                 {
61                         //TODO: validation
62                         if (row == null)
63                                 throw new ArgumentNullException("row", "'row' argument cannot be null.");
64
65                         if (row.Table != this.table)
66                                 throw new ArgumentException ("This row already belongs to another table.");
67                         
68                         // If row id is not -1, we know that it is in the collection.
69                         if (row.RowID != -1)
70                                 throw new ArgumentException ("This row already belongs to this table.");
71                         
72
73                         if ((table.DataSet == null || table.DataSet.EnforceConstraints) && !table._duringDataLoad)
74                                 // we have to check that the new row doesn't colide with existing row
75                                 ValidateDataRowInternal(row);
76                         
77                         row.HasParentCollection = true;
78                         list.Add (row);
79                         // Set the row id.
80                         row.RowID = list.Count - 1;
81                         row.AttachRow ();
82                         row.Table.ChangedDataRow (row, DataRowAction.Add);
83                 }
84
85                 /// <summary>
86                 /// Creates a row using specified values and adds it to the DataRowCollection.
87                 /// </summary>
88                 public virtual DataRow Add (object[] values) 
89                 {
90                         DataRow row = table.NewRow ();
91                         row.ItemArray = values;
92                         Add (row);
93                         return row;
94                 }
95
96                 /// <summary>
97                 /// Clears the collection of all rows.
98                 /// </summary>
99                 public void Clear () 
100                 {
101                         if (this.table.DataSet != null)
102                         {
103                                 foreach (DataTable table in this.table.DataSet.Tables)
104                                 {
105                                         foreach (Constraint c in table.Constraints)
106                                         {
107                                                 if (c is ForeignKeyConstraint)
108                                                 {
109                                                         if (((ForeignKeyConstraint) c).RelatedTable.Equals(this.table))
110                                                                 throw new InvalidConstraintException("Cannot clear table Parent because ForeignKeyConstraint " + c.ConstraintName + " enforces Child.");
111                                                 }
112                                         }
113                                 }
114                         }
115                         list.Clear ();
116                 }
117
118                 /// <summary>
119                 /// Gets a value indicating whether the primary key of any row in the collection contains
120                 /// the specified value.
121                 /// </summary>
122                 public bool Contains (object key) 
123                 {
124                         return Find (key) != null;
125                 }
126
127                 /// <summary>
128                 /// Gets a value indicating whether the primary key column(s) of any row in the 
129                 /// collection contains the values specified in the object array.
130                 /// </summary>
131                 public bool Contains (object[] keys) 
132                 {
133                         if (table.PrimaryKey.Length != keys.Length)
134                                 throw new ArgumentException ("Expecting " + table.PrimaryKey.Length + " value(s) for the key " + 
135                                                              "being indexed, but received " + keys.Length + " value(s).");
136
137                         return Find (keys) != null;
138                 }
139
140                 /// <summary>
141                 /// Gets the row specified by the primary key value.
142                 /// </summary>
143                 [MonoTODO]
144                 public DataRow Find (object key) 
145                 {
146                         if (table.PrimaryKey.Length == 0)
147                                 throw new MissingPrimaryKeyException ("Table doesn't have a primary key.");
148                         if (table.PrimaryKey.Length > 1)
149                                 throw new ArgumentException ("Expecting " + table.PrimaryKey.Length + 
150                                                              " value(s) for the key being indexed, but received 1 value(s).");
151
152                         string primColumnName = table.PrimaryKey [0].ColumnName;
153                         Type coltype = null;
154                         object newKey = null;
155                         
156                         foreach (DataRow row in this) {
157                                 
158                                 if (row.RowState != DataRowState.Deleted)
159                                 {
160                                         object primValue = row [primColumnName];
161                                         if (key == null) 
162                                         {
163                                                 if (primValue == null)
164                                                         return row;
165                                                 else 
166                                                         continue;
167                                         }
168                                        
169                                         newKey = Convert.ChangeType (key, Type.GetTypeCode(primValue.GetType ()));
170
171                                         if (primValue.Equals (newKey))
172                                                 return row;
173                                 }
174                         }
175                                                 
176                         // FIXME: is the correct value null?
177                         return null;
178                 }
179
180                 /// <summary>
181                 /// Gets the row containing the specified primary key values.
182                 /// </summary>
183                 [MonoTODO]
184                 public DataRow Find (object[] keys) 
185                 {
186                         if (table.PrimaryKey.Length == 0)
187                                 throw new MissingPrimaryKeyException ("Table doesn't have a primary key.");
188
189                         string  [] primColumnNames = new string [table.PrimaryKey.Length];
190                         
191                         for (int i = 0; i < primColumnNames.Length; i++)
192                                 primColumnNames [i] = table.PrimaryKey [i].ColumnName;
193
194                         Type coltype = null;
195                         object newKey = null;
196                         
197                         foreach (DataRow row in this) {
198                                 
199                                 if (row.RowState != DataRowState.Deleted)
200                                 {
201                                         bool eq = true;
202                                         for (int i = 0; i < keys.Length; i++) 
203                                         {
204                                         
205                                                 object primValue = row [primColumnNames [i]];
206                                                 object keyValue = keys [i];
207                                                 if (keyValue == null) 
208                                                 {
209                                                         if (primValue == null)
210                                                                 return row;
211                                                         else 
212                                                                 continue;
213                                                 }
214                                                                        
215                                                 newKey = Convert.ChangeType (keyValue, Type.GetTypeCode(primValue.GetType ()));
216
217                                                 if (!primValue.Equals (newKey)) 
218                                                 {
219                                                         eq = false;
220                                                         break;
221                                                 }                                               
222                                         }
223
224                                         if (eq)
225                                                 return row;
226                                 }
227                         }
228                                                 
229                         // FIXME: is the correct value null?
230                         return null;
231                 }
232
233                 /// <summary>
234                 /// Inserts a new row into the collection at the specified location.
235                 /// </summary>
236                 public void InsertAt (DataRow row, int pos) 
237                 {
238                         if (pos < 0)
239                                 throw new IndexOutOfRangeException ("The row insert position " + pos + " is invalid.");
240                         
241                         if (row == null)
242                                 throw new ArgumentNullException("row", "'row' argument cannot be null.");
243         
244                         if (row.Table != this.table)
245                                 throw new ArgumentException ("This row already belongs to another table.");
246
247                         // If row id is not -1, we know that it is in the collection.
248                         if (row.RowID != -1)
249                                 throw new ArgumentException ("This row already belongs to this table.");
250                         
251                         if ((table.DataSet == null || table.DataSet.EnforceConstraints) && !table._duringDataLoad)
252                                 // we have to check that the new row doesn't colide with existing row
253                                 ValidateDataRowInternal(row);
254                                 
255                         if (pos >= list.Count)
256                                 list.Add (row);
257                         else
258                                 list.Insert (pos, row);
259                                 
260                         row.HasParentCollection = true;
261                         row.AttachRow ();
262                         row.Table.ChangedDataRow (row, DataRowAction.Add);
263                 }
264
265                 /// <summary>
266                 /// Removes the specified DataRow from the internal list. Used by DataRow to commit the removing.
267                 /// </summary>
268                 internal void RemoveInternal (DataRow row) {
269                         if (row == null) {
270                                 throw new IndexOutOfRangeException ("The given datarow is not in the current DataRowCollection.");
271                         }
272                         int index = list.IndexOf(row);
273                         if (index < 0) {
274                                 throw new IndexOutOfRangeException ("The given datarow is not in the current DataRowCollection.");
275                         }
276                         list.RemoveAt(index);
277                 }
278
279                 /// <summary>
280                 /// Removes the specified DataRow from the collection.
281                 /// </summary>
282                 public void Remove (DataRow row) 
283                 {
284                         if (row == null)
285                                 throw new IndexOutOfRangeException ("The given datarow is not in the current DataRowCollection.");
286                         int index = list.IndexOf(row);
287                         if (index < 0)
288                                 throw new IndexOutOfRangeException ("The given datarow is not in the current DataRowCollection.");
289                         row.Delete();
290                         // if the row was in added state it will be in Detached state after the
291                         // delete operation, so we have to check it.
292                         if (row.RowState != DataRowState.Detached)
293                                 row.AcceptChanges();
294                 }
295
296                 /// <summary>
297                 /// Removes the row at the specified index from the collection.
298                 /// </summary>
299                 public void RemoveAt (int index) 
300                 {                       
301                         if (index < 0 || index >= list.Count)
302                                 throw new IndexOutOfRangeException ("There is no row at position " + index + ".");
303                         DataRow row = (DataRow)list [index];
304                         row.Delete();
305                         row.AcceptChanges();
306                 }
307
308                 ///<summary>
309                 ///Internal method used to validate a given DataRow with respect
310                 ///to the DataRowCollection
311                 ///</summary>
312                 [MonoTODO]
313                 internal void ValidateDataRowInternal(DataRow row)
314                 {
315                         //first check for null violations.
316                         row.CheckNullConstraints();
317                         //FIXME: this validates constraints in the order they appear
318                         //in the collection. Most probably we need to do it in a 
319                         //specific order like unique/primary keys first, then Foreignkeys, etc
320                         foreach(Constraint constraint in table.Constraints)
321                         {
322                                 constraint.AssertConstraint(row);
323                         }
324
325                 }
326                 
327         }
328
329
330 }