6439772d06ec7995536eb488bcb19f42047366c3
[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                 public DataRow Find (object key) 
144                 {
145                         if (table.PrimaryKey.Length == 0)
146                                 throw new MissingPrimaryKeyException ("Table doesn't have a primary key.");
147                         if (table.PrimaryKey.Length > 1)
148                                 throw new ArgumentException ("Expecting " + table.PrimaryKey.Length + 
149                                                              " value(s) for the key being indexed, but received 1 value(s).");
150
151                         string primColumnName = table.PrimaryKey [0].ColumnName;
152                         Type coltype = null;
153                         object newKey = null;
154                         
155                         foreach (DataRow row in this) {
156                                 
157                                 if (row.RowState != DataRowState.Deleted)
158                                 {
159                                         object primValue = row [primColumnName];
160                                         if (key == null) 
161                                         {
162                                                 if (primValue == null)
163                                                         return row;
164                                                 else 
165                                                         continue;
166                                         }
167                                        
168                                         newKey = Convert.ChangeType (key, Type.GetTypeCode(primValue.GetType ()));
169
170                                         if (primValue.Equals (newKey))
171                                                 return row;
172                                 }
173                         }
174                                                 
175                         return null;
176                 }
177
178                 /// <summary>
179                 /// Gets the row containing the specified primary key values.
180                 /// </summary>
181                 public DataRow Find (object[] keys) 
182                 {
183                         if (table.PrimaryKey.Length == 0)
184                                 throw new MissingPrimaryKeyException ("Table doesn't have a primary key.");
185
186                         string  [] primColumnNames = new string [table.PrimaryKey.Length];
187                         
188                         for (int i = 0; i < primColumnNames.Length; i++)
189                                 primColumnNames [i] = table.PrimaryKey [i].ColumnName;
190
191                         Type coltype = null;
192                         object newKey = null;
193                         
194                         foreach (DataRow row in this) {
195                                 
196                                 if (row.RowState != DataRowState.Deleted)
197                                 {
198                                         bool eq = true;
199                                         for (int i = 0; i < keys.Length; i++) 
200                                         {
201                                         
202                                                 object primValue = row [primColumnNames [i]];
203                                                 object keyValue = keys [i];
204                                                 if (keyValue == null) 
205                                                 {
206                                                         if (primValue == null)
207                                                                 return row;
208                                                         else 
209                                                                 continue;
210                                                 }
211                                                                        
212                                                 newKey = Convert.ChangeType (keyValue, Type.GetTypeCode(primValue.GetType ()));
213
214                                                 if (!primValue.Equals (newKey)) 
215                                                 {
216                                                         eq = false;
217                                                         break;
218                                                 }                                               
219                                         }
220
221                                         if (eq)
222                                                 return row;
223                                 }
224                         }
225                                                 
226                         return null;
227                 }
228
229                 /// <summary>
230                 /// Inserts a new row into the collection at the specified location.
231                 /// </summary>
232                 public void InsertAt (DataRow row, int pos) 
233                 {
234                         if (pos < 0)
235                                 throw new IndexOutOfRangeException ("The row insert position " + pos + " is invalid.");
236                         
237                         if (row == null)
238                                 throw new ArgumentNullException("row", "'row' argument cannot be null.");
239         
240                         if (row.Table != this.table)
241                                 throw new ArgumentException ("This row already belongs to another table.");
242
243                         // If row id is not -1, we know that it is in the collection.
244                         if (row.RowID != -1)
245                                 throw new ArgumentException ("This row already belongs to this table.");
246                         
247                         if ((table.DataSet == null || table.DataSet.EnforceConstraints) && !table._duringDataLoad)
248                                 // we have to check that the new row doesn't colide with existing row
249                                 ValidateDataRowInternal(row);
250                                 
251                         if (pos >= list.Count)
252                                 list.Add (row);
253                         else
254                                 list.Insert (pos, row);
255                                 
256                         row.HasParentCollection = true;
257                         row.AttachRow ();
258                         row.Table.ChangedDataRow (row, DataRowAction.Add);
259                 }
260
261                 /// <summary>
262                 /// Removes the specified DataRow from the internal list. Used by DataRow to commit the removing.
263                 /// </summary>
264                 internal void RemoveInternal (DataRow row) {
265                         if (row == null) {
266                                 throw new IndexOutOfRangeException ("The given datarow is not in the current DataRowCollection.");
267                         }
268                         int index = list.IndexOf(row);
269                         if (index < 0) {
270                                 throw new IndexOutOfRangeException ("The given datarow is not in the current DataRowCollection.");
271                         }
272                         list.RemoveAt(index);
273                 }
274
275                 /// <summary>
276                 /// Removes the specified DataRow from the collection.
277                 /// </summary>
278                 public void Remove (DataRow row) 
279                 {
280                         if (row == null)
281                                 throw new IndexOutOfRangeException ("The given datarow is not in the current DataRowCollection.");
282                         int index = list.IndexOf(row);
283                         if (index < 0)
284                                 throw new IndexOutOfRangeException ("The given datarow is not in the current DataRowCollection.");
285                         row.Delete();
286                         // if the row was in added state it will be in Detached state after the
287                         // delete operation, so we have to check it.
288                         if (row.RowState != DataRowState.Detached)
289                                 row.AcceptChanges();
290                 }
291
292                 /// <summary>
293                 /// Removes the row at the specified index from the collection.
294                 /// </summary>
295                 public void RemoveAt (int index) 
296                 {                       
297                         if (index < 0 || index >= list.Count)
298                                 throw new IndexOutOfRangeException ("There is no row at position " + index + ".");
299                         DataRow row = (DataRow)list [index];
300                         row.Delete();
301                         row.AcceptChanges();
302                 }
303
304                 ///<summary>
305                 ///Internal method used to validate a given DataRow with respect
306                 ///to the DataRowCollection
307                 ///</summary>
308                 [MonoTODO]
309                 internal void ValidateDataRowInternal(DataRow row)
310                 {
311                         //first check for null violations.
312                         row.CheckNullConstraints();
313                         // This validates constraints in the specific order : 
314                         // first unique/primary keys first, then Foreignkeys, etc
315                         ArrayList uniqueConstraintsDone = new ArrayList();
316                         ArrayList foreignKeyConstraintsDone = new ArrayList();
317                         try {
318                                 foreach(Constraint constraint in table.Constraints.UniqueConstraints) {
319                                         constraint.AssertConstraint(row);
320                                         uniqueConstraintsDone.Add(constraint);
321                                 }
322                         
323                                 foreach(Constraint constraint in table.Constraints.ForeignKeyConstraints) {
324                                         constraint.AssertConstraint(row);
325                                         foreignKeyConstraintsDone.Add(constraint);
326                                 }
327                         }
328                         // if one of the AssertConstraint failed - we need to "rollback" all the changes
329                         // caused by AssertCoinstraint calls already succeeded
330                         catch(ConstraintException e) {
331                                 RollbackAsserts(row,foreignKeyConstraintsDone,uniqueConstraintsDone);
332                                 throw e;
333                         }
334                         catch(InvalidConstraintException e) {   
335                                 RollbackAsserts(row,foreignKeyConstraintsDone,uniqueConstraintsDone);
336                                 throw e;
337                         }
338                 }
339
340                 private void RollbackAsserts(DataRow row,ICollection foreignKeyConstraintsDone,
341                         ICollection uniqueConstraintsDone)
342                 {
343                         // if any of constraints assert failed - 
344                         // we have to rollback all the asserts scceeded
345                         // on order reverse to thier original execution
346                         foreach(Constraint constraint in foreignKeyConstraintsDone) {
347                                 constraint.RollbackAssert(row);
348                         }
349
350                         foreach(Constraint constraint in uniqueConstraintsDone) {
351                                 constraint.RollbackAssert(row);
352                         }
353                 }
354         }
355 }