Merge pull request #1496 from echampet/serializers
[mono.git] / mcs / class / System.Data / System.Data.Common / DbDataAdapter.cs
1 //
2 // System.Data.Common.DbDataAdapter.cs
3 //
4 // Author:
5 //   Rodrigo Moya (rodrigo@ximian.com)
6 //   Tim Coleman (tim@timcoleman.com)
7 //   Sureshkumar T <tsureshkumar@novell.com>
8 //   Veerapuram Varadhan  <vvaradhan@novell.com>
9 //
10 // (C) Ximian, Inc
11 // Copyright (C) Tim Coleman, 2002-2003
12 //
13
14 //
15 // Copyright (C) 2004, 2009 Novell, Inc (http://www.novell.com)
16 //
17 // Permission is hereby granted, free of charge, to any person obtaining
18 // a copy of this software and associated documentation files (the
19 // "Software"), to deal in the Software without restriction, including
20 // without limitation the rights to use, copy, modify, merge, publish,
21 // distribute, sublicense, and/or sell copies of the Software, and to
22 // permit persons to whom the Software is furnished to do so, subject to
23 // the following conditions:
24 // 
25 // The above copyright notice and this permission notice shall be
26 // included in all copies or substantial portions of the Software.
27 // 
28 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
29 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
30 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
31 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
32 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
33 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
34 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35 //
36
37 using System;
38 using System.Collections;
39 using System.ComponentModel;
40 using System.Data;
41 using System.Reflection;
42 using System.Runtime.InteropServices;
43
44 namespace System.Data.Common
45 {
46         public abstract class DbDataAdapter : DataAdapter, IDbDataAdapter, IDataAdapter, ICloneable
47         {
48                 #region Fields
49
50                 public const string DefaultSourceTableName = "Table";
51                 const string DefaultSourceColumnName = "Column";
52                 CommandBehavior _behavior = CommandBehavior.Default;
53
54                 IDbCommand _selectCommand;
55                 IDbCommand _updateCommand;
56                 IDbCommand _deleteCommand;
57                 IDbCommand _insertCommand;
58
59                 #endregion // Fields
60                 
61                 #region Constructors
62
63                 protected DbDataAdapter ()
64                 {
65                 }
66
67                 protected DbDataAdapter (DbDataAdapter adapter) : base (adapter)
68                 {
69                 }
70
71                 #endregion // Fields
72
73                 #region Properties
74
75                 protected internal CommandBehavior FillCommandBehavior {
76                         get { return _behavior; }
77                         set { _behavior = value; }
78                 }
79
80                 IDbCommand IDbDataAdapter.SelectCommand {
81                     get { return ((DbDataAdapter)this).SelectCommand; }
82                     set { ((DbDataAdapter)this).SelectCommand = (DbCommand)value; }
83                 }
84
85                 IDbCommand IDbDataAdapter.UpdateCommand{
86                     get { return ((DbDataAdapter)this).UpdateCommand; }
87                     set { ((DbDataAdapter)this).UpdateCommand = (DbCommand)value; }
88                 }
89                 
90                 IDbCommand IDbDataAdapter.DeleteCommand{
91                     get { return ((DbDataAdapter)this).DeleteCommand; }
92                     set { ((DbDataAdapter)this).DeleteCommand = (DbCommand)value; }
93                 }
94
95                 IDbCommand IDbDataAdapter.InsertCommand{
96                     get { return ((DbDataAdapter)this).InsertCommand; }
97                     set { ((DbDataAdapter)this).InsertCommand = (DbCommand)value; }
98                 }
99                 
100                 [Browsable (false)]
101                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
102                 public DbCommand SelectCommand {
103                     get {
104                                         return (DbCommand) _selectCommand;
105                                         //return (DbCommand) ((IDbDataAdapter)this).SelectCommand; 
106                         }
107                     set {
108                                         if (_selectCommand != value) {
109                                                 _selectCommand = value;
110                                                 ((IDbDataAdapter)this).SelectCommand = value; 
111                                         }
112                         }
113                 }
114
115                 [Browsable (false)]
116                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
117                 public DbCommand DeleteCommand {
118                     get {
119                                         return (DbCommand) _deleteCommand;
120                                         //return (DbCommand) ((IDbDataAdapter)this).DeleteCommand; 
121                         }
122                     set {
123                                         if (_deleteCommand != value) {
124                                                 _deleteCommand = value;
125                                                 ((IDbDataAdapter)this).DeleteCommand = value; 
126                                         }
127                         }
128                 }
129
130                 [Browsable (false)]
131                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
132                 public DbCommand InsertCommand {
133                     get {
134                                         return (DbCommand) _insertCommand;
135                                         //return (DbCommand) ((IDbDataAdapter)this).InsertCommand; 
136                         }
137                     set {
138                                         if (_insertCommand != value) {
139                                                 _insertCommand = value;
140                                                 ((IDbDataAdapter)this).InsertCommand = value; 
141                                         }
142                         }
143                 }
144
145                 [Browsable (false)]
146                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
147                 public DbCommand UpdateCommand {
148                     get {
149                                         return (DbCommand) _updateCommand;
150                                         //return (DbCommand) ((IDbDataAdapter)this).DeleteCommand; 
151                         }
152                     set {
153                                         if (_updateCommand != value) {
154                                                 _updateCommand = value;
155                                                 ((IDbDataAdapter)this).UpdateCommand = value; 
156                                         }
157                         }
158                 }
159
160                 [DefaultValue (1)]
161                 public virtual int UpdateBatchSize {
162                         get { return 1; }
163                         set {
164                                 if (value != 1)
165                                         throw new NotSupportedException ();
166                         }
167                 }
168
169                 #endregion // Properties
170                 
171                 #region Methods
172
173                 protected virtual RowUpdatedEventArgs CreateRowUpdatedEvent (DataRow dataRow, IDbCommand command,
174                                                                              StatementType statementType,
175                                                                              DataTableMapping tableMapping)
176                 {
177                         return new RowUpdatedEventArgs (dataRow, command, statementType, tableMapping);
178                 }
179
180                 protected virtual RowUpdatingEventArgs CreateRowUpdatingEvent (DataRow dataRow, IDbCommand command,
181                                                                                StatementType statementType,
182                                                                                DataTableMapping tableMapping)
183                 {
184                         return new RowUpdatingEventArgs (dataRow, command, statementType, tableMapping);
185                 }
186
187                 protected virtual void OnRowUpdated (RowUpdatedEventArgs value)
188                 {
189                         if (Events ["RowUpdated"] != null) {
190                                 Delegate [] rowUpdatedList = Events ["RowUpdated"].GetInvocationList ();
191                                 foreach (Delegate rowUpdated in rowUpdatedList) {
192                                         MethodInfo rowUpdatedMethod = rowUpdated.Method;
193                                         rowUpdatedMethod.Invoke (value, null);
194                                 }
195                         }
196                 }
197
198                 protected virtual void OnRowUpdating (RowUpdatingEventArgs value)
199                 {
200                         if (Events ["RowUpdating"] != null) {
201                                 Delegate [] rowUpdatingList = Events ["RowUpdating"].GetInvocationList ();
202                                 foreach (Delegate rowUpdating in rowUpdatingList) {
203                                         MethodInfo rowUpdatingMethod = rowUpdating.Method;
204                                         rowUpdatingMethod.Invoke (value, null);
205                                 }
206                         }
207                 }
208
209                 protected override void Dispose (bool disposing)
210                 {
211                         if (disposing) {
212                                 IDbDataAdapter da = (IDbDataAdapter) this;
213                                 if (da.SelectCommand != null) {
214                                         da.SelectCommand.Dispose();
215                                         da.SelectCommand = null;
216                                 }
217                                 if (da.InsertCommand != null) {
218                                         da.InsertCommand.Dispose();
219                                         da.InsertCommand = null;
220                                 }
221                                 if (da.UpdateCommand != null) {
222                                         da.UpdateCommand.Dispose();
223                                         da.UpdateCommand = null;
224                                 }
225                                 if (da.DeleteCommand != null) {
226                                         da.DeleteCommand.Dispose();
227                                         da.DeleteCommand = null;
228                                 }
229                         }
230                 }
231
232                 public override int Fill (DataSet dataSet)
233                 {
234                         return Fill (dataSet, 0, 0, DefaultSourceTableName, ((IDbDataAdapter) this).SelectCommand, _behavior);
235                 }
236
237                 public int Fill (DataTable dataTable)
238                 {
239                         if (dataTable == null)
240                                 throw new ArgumentNullException ("DataTable");
241
242                         return Fill (dataTable, ((IDbDataAdapter) this).SelectCommand, _behavior);
243                 }
244
245                 public int Fill (DataSet dataSet, string srcTable)
246                 {
247                         return Fill (dataSet, 0, 0, srcTable, ((IDbDataAdapter) this).SelectCommand, _behavior);
248                 }
249
250
251                 protected virtual int Fill (DataTable dataTable, IDbCommand command, CommandBehavior behavior)
252                 {
253                         CommandBehavior commandBehavior = behavior;
254
255                         // first see that the connection is not close.
256                         if (command.Connection.State == ConnectionState.Closed) {
257                                 command.Connection.Open ();
258                                 commandBehavior |= CommandBehavior.CloseConnection;
259                         }
260                         return Fill (dataTable, command.ExecuteReader (commandBehavior));
261                 }
262
263                 public int Fill (DataSet dataSet, int startRecord, int maxRecords, string srcTable)
264                 {
265                         return this.Fill (dataSet, startRecord, maxRecords, srcTable, ((IDbDataAdapter) this).SelectCommand, _behavior);
266                 }
267
268                 [MonoTODO]
269                 public int Fill (int startRecord, int maxRecords, params DataTable[] dataTables)
270                 {
271                         throw new NotImplementedException ();
272                 }
273
274                 [MonoTODO]
275                 protected virtual int Fill (DataTable[] dataTables, int startRecord, int maxRecords, IDbCommand command, CommandBehavior behavior)
276                 {
277                         throw new NotImplementedException ();
278                 }
279
280                 protected virtual int Fill (DataSet dataSet, int startRecord, int maxRecords, string srcTable, IDbCommand command, CommandBehavior behavior)
281                 {
282                         if (command.Connection == null)
283                                 throw new InvalidOperationException ("Connection state is closed");
284
285                         if (MissingSchemaAction == MissingSchemaAction.AddWithKey)
286                                 behavior |= CommandBehavior.KeyInfo;
287                         CommandBehavior commandBehavior = behavior;
288
289                         if (command.Connection.State == ConnectionState.Closed) {
290                                 command.Connection.Open ();
291                                 commandBehavior |= CommandBehavior.CloseConnection;
292                         }
293                         return Fill (dataSet, srcTable, command.ExecuteReader (commandBehavior),
294                                 startRecord, maxRecords);
295                 }
296
297                 /// <summary>
298                 /// Fills the given datatable using values from reader. if a value 
299                 /// for a column is  null, that will be filled with default value. 
300                 /// </summary>
301                 /// <returns>No. of rows affected </returns>
302                 internal static int FillFromReader (DataTable table,
303                                                     IDataReader reader,
304                                                     int start,
305                                                     int length,
306                                                     int [] mapping,
307                                                     LoadOption loadOption
308                                                     )
309                 {
310                         if (reader.FieldCount == 0)
311                                 return 0 ;
312
313                         for (int i = 0; i < start; i++)
314                                 reader.Read ();
315
316                         int counter = 0;
317                         object [] values = new object [mapping.Length];
318                         while (reader.Read () && (length == 0 || counter < length)) {
319                                 for (int i = 0 ; i < mapping.Length; i++)
320                                         values [i] = mapping [i] < 0 ? null : reader [mapping [i]];
321                                 table.BeginLoadData ();
322                                 table.LoadDataRow (values, loadOption);
323                                 table.EndLoadData ();
324                                 counter++;
325                         }
326                         return counter;
327                 }
328
329                 internal static int FillFromReader (DataTable table,
330                                                     IDataReader reader,
331                                                     int start,
332                                                     int length,
333                                                     int [] mapping,
334                                                     LoadOption loadOption,
335                                                     FillErrorEventHandler errorHandler)
336                 {
337                         if (reader.FieldCount == 0)
338                                 return 0 ;
339
340                         for (int i = 0; i < start; i++)
341                                 reader.Read ();
342
343                         int counter = 0;
344                         object [] values = new object [mapping.Length];
345                         while (reader.Read () && (length == 0 || counter < length)) {
346                                 for (int i = 0 ; i < mapping.Length; i++)
347                                         values [i] = mapping [i] < 0 ? null : reader [mapping [i]];
348                                 table.BeginLoadData ();
349                                 try {
350                                         table.LoadDataRow (values, loadOption);
351                                 } catch (Exception e) {
352                                         FillErrorEventArgs args = new FillErrorEventArgs (table, values);
353                                         args.Errors = e;
354                                         args.Continue = false;
355                                         errorHandler (table, args);
356                                         // if args.Continue is not set to true or if a handler is not set, rethrow the error..
357                                         if(!args.Continue)
358                                                 throw e;
359                                 }
360                                 table.EndLoadData ();
361                                 counter++;
362                         }
363                         return counter;
364                 }
365
366                 public override DataTable [] FillSchema (DataSet dataSet, SchemaType schemaType)
367                 {
368                         return FillSchema (dataSet, schemaType, ((IDbDataAdapter) this).SelectCommand, DefaultSourceTableName, _behavior);
369                 }
370
371                 public DataTable FillSchema (DataTable dataTable, SchemaType schemaType)
372                 {
373                         return FillSchema (dataTable, schemaType, ((IDbDataAdapter) this).SelectCommand, _behavior);
374                 }
375
376                 public DataTable [] FillSchema (DataSet dataSet, SchemaType schemaType, string srcTable)
377                 {
378                         return FillSchema (dataSet, schemaType, ((IDbDataAdapter) this).SelectCommand, srcTable, _behavior);
379                 }
380
381                 protected virtual DataTable FillSchema (DataTable dataTable, SchemaType schemaType, IDbCommand command, CommandBehavior behavior)
382                 {
383                         if (dataTable == null)
384                                 throw new ArgumentNullException ("DataTable");
385
386                         behavior |= CommandBehavior.SchemaOnly | CommandBehavior.KeyInfo;
387                         if (command.Connection.State == ConnectionState.Closed) {
388                                 command.Connection.Open ();
389                                 behavior |= CommandBehavior.CloseConnection;
390                         }
391
392                         IDataReader reader = command.ExecuteReader (behavior);
393                         try {
394                                 string tableName =  SetupSchema (schemaType, dataTable.TableName);
395                                 if (tableName != null) {
396                                         // FillSchema should add the KeyInfo unless MissingSchemaAction
397                                         // is set to Ignore or Error.
398                                         MissingSchemaAction schemaAction = MissingSchemaAction;
399                                         if (!(schemaAction == MissingSchemaAction.Ignore ||
400                                                 schemaAction == MissingSchemaAction.Error))
401                                                 schemaAction = MissingSchemaAction.AddWithKey;
402
403                                         BuildSchema (reader, dataTable, schemaType, schemaAction,
404                                                 MissingMappingAction, TableMappings);
405                                 }
406                         } finally {
407                                 reader.Close ();
408                         }
409                         return dataTable;
410                 }
411
412                 protected virtual DataTable[] FillSchema (DataSet dataSet, SchemaType schemaType, IDbCommand command, string srcTable, CommandBehavior behavior)
413                 {
414                         if (dataSet == null)
415                                 throw new ArgumentNullException ("DataSet");
416
417                         behavior |= CommandBehavior.SchemaOnly | CommandBehavior.KeyInfo;
418                         if (command.Connection.State == ConnectionState.Closed) {
419                                 command.Connection.Open ();
420                                 behavior |= CommandBehavior.CloseConnection;
421                         }
422
423                         IDataReader reader = command.ExecuteReader (behavior);
424                         ArrayList output = new ArrayList ();
425                         string tableName = srcTable;
426                         int index = 0;
427                         DataTable table;
428                         try {
429                                 // FillSchema should add the KeyInfo unless MissingSchemaAction
430                                 // is set to Ignore or Error.
431                                 MissingSchemaAction schemaAction = MissingSchemaAction;
432                                 if (!(MissingSchemaAction == MissingSchemaAction.Ignore ||
433                                         MissingSchemaAction == MissingSchemaAction.Error))
434                                         schemaAction = MissingSchemaAction.AddWithKey;
435
436                                 do {
437                                         tableName = SetupSchema (schemaType, tableName);
438                                         if (tableName != null) {
439                                                 if (dataSet.Tables.Contains (tableName))
440                                                         table = dataSet.Tables [tableName];
441                                                 else {
442                                                         // Do not create schema if MissingSchemAction is set to Ignore
443                                                         if (this.MissingSchemaAction == MissingSchemaAction.Ignore)
444                                                                 continue;
445                                                         table =  dataSet.Tables.Add (tableName);
446                                                 }
447                                                 
448                                                 BuildSchema (reader, table, schemaType, schemaAction,
449                                                         MissingMappingAction, TableMappings);
450                                                 output.Add (table);
451                                                 tableName = String.Format ("{0}{1}", srcTable, ++index);
452                                         }
453                                 }while (reader.NextResult ());
454                         } finally {
455                                 reader.Close ();
456                         }
457                         return (DataTable []) output.ToArray (typeof (DataTable));
458                 }
459
460                 [EditorBrowsable (EditorBrowsableState.Advanced)]
461                 public override IDataParameter[] GetFillParameters ()
462                 {
463                         IDbCommand selectCmd = ((IDbDataAdapter) this).SelectCommand;
464                         IDataParameter[] parameters = new IDataParameter [selectCmd.Parameters.Count];
465                         selectCmd.Parameters.CopyTo (parameters, 0);
466                         return parameters;
467                 }
468                 
469                 [MonoTODO]
470                 [Obsolete ("use 'protected DbDataAdapter(DbDataAdapter)' ctor")]
471                 object ICloneable.Clone ()
472                 {
473                         throw new NotImplementedException ();
474                 }
475
476                 public int Update (DataRow [] dataRows)
477                 {
478                         if (dataRows == null)
479                                 throw new ArgumentNullException("dataRows");
480                         
481                         if (dataRows.Length == 0)
482                                 return 0;
483
484                         if (dataRows [0] == null)
485                                 throw new ArgumentException("dataRows[0].");
486
487                         DataTable table = dataRows [0].Table;
488                         if (table == null)
489                                 throw new ArgumentException("table is null reference.");
490                         
491                         // all rows must be in the same table
492                         for (int i = 0; i < dataRows.Length; i++) {
493                                 if (dataRows [i] == null)
494                                         throw new ArgumentException ("dataRows[" + i + "].");
495                                 if (dataRows [i].Table != table)
496                                         throw new ArgumentException(
497                                                                     " DataRow["
498                                                                     + i
499                                                                     + "] is from a different DataTable than DataRow[0].");
500                         }
501                         
502                         // get table mapping for this rows
503                         DataTableMapping tableMapping = TableMappings.GetByDataSetTable(table.TableName);
504                         if (tableMapping == null) {
505                                 tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction(
506                                                                                                         TableMappings,
507                                                                                                         table.TableName,
508                                                                                                         table.TableName,
509                                                                                                         MissingMappingAction);
510                                 if (tableMapping != null) {
511                                         foreach (DataColumn col in table.Columns) {
512                                                 if (tableMapping.ColumnMappings.IndexOf (col.ColumnName) >= 0)
513                                                         continue;
514                                                 DataColumnMapping columnMapping = DataColumnMappingCollection.GetColumnMappingBySchemaAction (tableMapping.ColumnMappings, col.ColumnName, MissingMappingAction);
515                                                 if (columnMapping == null)
516                                                         columnMapping = new DataColumnMapping (col.ColumnName, col.ColumnName);
517                                                 tableMapping.ColumnMappings.Add (columnMapping);
518                                         }
519                                 } else {
520                                         ArrayList cmc = new ArrayList ();
521                                         foreach (DataColumn col in table.Columns)
522                                                 cmc.Add (new DataColumnMapping (col.ColumnName, col.ColumnName));
523                                         tableMapping =
524                                                 new DataTableMapping (
525                                                                       table.TableName,
526                                                                       table.TableName,
527                                                                       cmc.ToArray (typeof (DataColumnMapping)) as DataColumnMapping []);
528                                 }
529                         }
530
531                         DataRow[] copy = table.NewRowArray (dataRows.Length);
532                         Array.Copy (dataRows, 0, copy, 0, dataRows.Length);
533                         return Update (copy, tableMapping);
534                 }
535
536                 public override int Update (DataSet dataSet)
537                 {
538                         return Update (dataSet, DefaultSourceTableName);
539                 }
540
541                 public int Update (DataTable dataTable)
542                 {
543                         /*
544                           int index = TableMappings.IndexOfDataSetTable (dataTable.TableName);
545                           if (index < 0)
546                           throw new ArgumentException ();
547                           return Update (dataTable, TableMappings [index]);
548                         */
549                         DataTableMapping tableMapping = TableMappings.GetByDataSetTable (dataTable.TableName);
550                         if (tableMapping == null) {
551                                 tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction (
552                                                                                                          TableMappings,
553                                                                                                          dataTable.TableName,
554                                                                                                          dataTable.TableName,
555                                                                                                          MissingMappingAction);
556                                 if (tableMapping != null) {
557                                         foreach (DataColumn col in dataTable.Columns) {
558                                                 if (tableMapping.ColumnMappings.IndexOf (col.ColumnName) >= 0)
559                                                         continue;
560                                                 DataColumnMapping columnMapping = DataColumnMappingCollection.GetColumnMappingBySchemaAction (tableMapping.ColumnMappings, col.ColumnName, MissingMappingAction);
561                                                 if (columnMapping == null)
562                                                         columnMapping = new DataColumnMapping (col.ColumnName, col.ColumnName);
563                                                 tableMapping.ColumnMappings.Add (columnMapping);
564                                         }
565                                 } else {
566                                         ArrayList cmc = new ArrayList ();
567                                         foreach (DataColumn col in dataTable.Columns)
568                                                 cmc.Add (new DataColumnMapping (col.ColumnName, col.ColumnName));
569                                         tableMapping =
570                                                 new DataTableMapping (
571                                                                       dataTable.TableName,
572                                                                       dataTable.TableName,
573                                                                       cmc.ToArray (typeof (DataColumnMapping)) as DataColumnMapping []);
574                                 }
575                         }
576                         return Update (dataTable, tableMapping);
577                 }
578
579                 private int Update (DataTable dataTable, DataTableMapping tableMapping)
580                 {
581                         DataRow [] rows = dataTable.NewRowArray(dataTable.Rows.Count);
582                         dataTable.Rows.CopyTo (rows, 0);
583                         return Update (rows, tableMapping);
584                 }
585
586                 protected virtual int Update (DataRow [] dataRows, DataTableMapping tableMapping)
587                 {
588                         int updateCount = 0;
589                         foreach (DataRow row in dataRows) {
590                                 StatementType statementType = StatementType.Update;
591                                 IDbCommand command = null;
592                                 string commandName = String.Empty;
593
594                                 switch (row.RowState) {
595                                 case DataRowState.Added:
596                                         statementType = StatementType.Insert;
597                                         command = ((IDbDataAdapter) this).InsertCommand;
598                                         commandName = "Insert";
599                                         break;
600                                 case DataRowState.Deleted:
601                                         statementType = StatementType.Delete;
602                                         command = ((IDbDataAdapter) this).DeleteCommand;
603                                         commandName = "Delete";
604                                         break;
605                                 case DataRowState.Modified:
606                                         statementType = StatementType.Update;
607                                         command = ((IDbDataAdapter) this).UpdateCommand;
608                                         commandName = "Update";
609                                         break;
610                                 case DataRowState.Unchanged:
611                                 case DataRowState.Detached:
612                                         continue;
613                                 }
614
615                                 RowUpdatingEventArgs argsUpdating = CreateRowUpdatingEvent (row, command, statementType, tableMapping);
616                                 row.RowError = String.Empty;
617                                 OnRowUpdating (argsUpdating);
618                                 switch (argsUpdating.Status) {
619                                 case UpdateStatus.Continue :
620                                         //continue in update operation
621                                         break;
622                                 case UpdateStatus.ErrorsOccurred :
623                                         if (argsUpdating.Errors == null)
624                                                 argsUpdating.Errors = ExceptionHelper.RowUpdatedError();
625                                         row.RowError += argsUpdating.Errors.Message;
626                                         if (!ContinueUpdateOnError)
627                                                 throw argsUpdating.Errors;
628                                         continue;
629                                 case UpdateStatus.SkipAllRemainingRows :
630                                         return updateCount;
631                                 case UpdateStatus.SkipCurrentRow :
632                                         updateCount++;
633                                         continue;
634                                 default :
635                                         throw ExceptionHelper.InvalidUpdateStatus (argsUpdating.Status);
636                                 }
637                                 command = argsUpdating.Command;
638                                 try {
639                                         if (command != null) {
640                                                 DataColumnMappingCollection columnMappings = tableMapping.ColumnMappings;
641                                                 foreach (IDataParameter parameter in command.Parameters) {
642                                                         if ((parameter.Direction & ParameterDirection.Input) == 0)
643                                                                 continue;
644
645                                                         DataRowVersion rowVersion = parameter.SourceVersion;
646                                                         // Parameter version is ignored for non-update commands
647                                                         if (statementType == StatementType.Delete)
648                                                                 rowVersion = DataRowVersion.Original;
649
650                                                         string dsColumnName = parameter.SourceColumn;
651                                                         if (columnMappings.Contains(dsColumnName)) {
652                                                                 dsColumnName = columnMappings [dsColumnName].DataSetColumn;
653                                                                 parameter.Value = row [dsColumnName, rowVersion];
654                                                         } else {
655                                                                 parameter.Value = null;
656                                                         }
657
658                                                         DbParameter nullCheckParam = parameter as DbParameter;
659
660                                                         if (nullCheckParam != null && nullCheckParam.SourceColumnNullMapping) {
661                                                                 if (parameter.Value != null && parameter.Value != DBNull.Value)
662                                                                         nullCheckParam.Value = 0;
663                                                                 else
664                                                                         nullCheckParam.Value = 1;
665                                                                 nullCheckParam = null;
666                                                         }
667                                                 }
668                                         }
669                                 } catch (Exception e) {
670                                         argsUpdating.Errors = e;
671                                         argsUpdating.Status = UpdateStatus.ErrorsOccurred;
672                                 }
673
674                                 IDataReader reader = null;
675                                 try {
676                                         if (command == null)
677                                                 throw ExceptionHelper.UpdateRequiresCommand (commandName);
678                                 
679                                         CommandBehavior commandBehavior = CommandBehavior.Default;
680                                         if (command.Connection.State == ConnectionState.Closed) {
681                                                 command.Connection.Open ();
682                                                 commandBehavior |= CommandBehavior.CloseConnection;
683                                         }
684                                 
685                                         // use ExecuteReader because we want to use the commandbehavior parameter.
686                                         // so the connection will be closed if needed.
687                                         reader = command.ExecuteReader (commandBehavior);
688
689                                         // update the current row, if the update command returns any resultset
690                                         // ignore other than the first record.
691                                         DataColumnMappingCollection columnMappings = tableMapping.ColumnMappings;
692
693                                         if (command.UpdatedRowSource == UpdateRowSource.Both ||
694                                             command.UpdatedRowSource == UpdateRowSource.FirstReturnedRecord) {
695                                                 if (reader.Read ()){
696                                                         DataTable retSchema = reader.GetSchemaTable ();
697                                                         foreach (DataRow dr in retSchema.Rows) {
698                                                                 string columnName = dr ["ColumnName"].ToString ();
699                                                                 string dstColumnName = columnName;
700                                                                 if (columnMappings != null &&
701                                                                     columnMappings.Contains(columnName))
702                                                                         dstColumnName = columnMappings [dstColumnName].DataSetColumn;
703                                                                 DataColumn dstColumn = row.Table.Columns [dstColumnName];
704                                                                 if (dstColumn == null
705                                                                     || (dstColumn.Expression != null
706                                                                         && dstColumn.Expression.Length > 0))
707                                                                         continue;
708                                                                 // info from : http://www.error-bank.com/microsoft.public.dotnet.framework.windowsforms.databinding/
709                                                                 // _35_hcsyiv0dha.2328@tk2msftngp10.phx.gbl_Thread.aspx
710                                                                 // disable readonly for non-expression columns.
711                                                                 bool readOnlyState = dstColumn.ReadOnly;
712                                                                 dstColumn.ReadOnly = false;
713                                                                 try {
714                                                                         row [dstColumnName] = reader [columnName];
715                                                                 } finally {
716                                                                         dstColumn.ReadOnly = readOnlyState;
717                                                                 }
718                                                         }
719                                                 }
720                                         }
721                                         reader.Close ();
722
723                                         int tmp = reader.RecordsAffected; // records affected is valid only after closing reader
724                                         // if the execute does not effect any rows we throw an exception.
725                                         if (tmp == 0)
726                                                 throw new DBConcurrencyException("Concurrency violation: the " + 
727                                                         commandName +"Command affected 0 records.", null,
728                                                         new DataRow [] { row });
729                                         updateCount += tmp;
730
731                                         if (command.UpdatedRowSource == UpdateRowSource.Both ||
732                                             command.UpdatedRowSource == UpdateRowSource.OutputParameters) {
733                                                 // Update output parameters to row values
734                                                 foreach (IDataParameter parameter in command.Parameters) {
735                                                         if (parameter.Direction != ParameterDirection.InputOutput
736                                                             && parameter.Direction != ParameterDirection.Output
737                                                             && parameter.Direction != ParameterDirection.ReturnValue)
738                                                                 continue;
739
740                                                         string dsColumnName = parameter.SourceColumn;
741                                                         if (columnMappings != null &&
742                                                             columnMappings.Contains(parameter.SourceColumn))
743                                                                 dsColumnName = columnMappings [parameter.SourceColumn].DataSetColumn;
744                                                         DataColumn dstColumn = row.Table.Columns [dsColumnName];
745                                                         if (dstColumn == null
746                                                             || (dstColumn.Expression != null 
747                                                                 && dstColumn.Expression.Length > 0))
748                                                                 continue;
749                                                         bool readOnlyState = dstColumn.ReadOnly;
750                                                         dstColumn.ReadOnly  = false;
751                                                         try {
752                                                                 row [dsColumnName] = parameter.Value;
753                                                         } finally {
754                                                                 dstColumn.ReadOnly = readOnlyState;
755                                                         }
756                                                 }
757                                         }
758
759                                         RowUpdatedEventArgs updatedArgs = CreateRowUpdatedEvent (row, command, statementType, tableMapping);
760                                         OnRowUpdated (updatedArgs);
761                                         switch (updatedArgs.Status) {
762                                         case UpdateStatus.Continue:
763                                                 break;
764                                         case UpdateStatus.ErrorsOccurred:
765                                                 if (updatedArgs.Errors == null)
766                                                         updatedArgs.Errors = ExceptionHelper.RowUpdatedError();
767                                                 row.RowError += updatedArgs.Errors.Message;
768                                                 if (!ContinueUpdateOnError)
769                                                         throw updatedArgs.Errors;
770                                                 break;
771                                         case UpdateStatus.SkipCurrentRow:
772                                                 continue;
773                                         case UpdateStatus.SkipAllRemainingRows:
774                                                 return updateCount;
775                                         }
776                                         if (!AcceptChangesDuringUpdate)
777                                                 continue;
778                                         row.AcceptChanges ();
779                                 } catch (Exception e) {
780                                         row.RowError = e.Message;
781                                         if (!ContinueUpdateOnError)
782                                                 throw e;
783                                 } finally {
784                                         if (reader != null && ! reader.IsClosed)
785                                                 reader.Close ();
786                                 }
787                         }
788                         return updateCount;
789                 }
790
791                 public int Update (DataSet dataSet, string srcTable)
792                 {
793                         MissingMappingAction mappingAction = MissingMappingAction;
794
795                         if (mappingAction == MissingMappingAction.Ignore)
796                                 mappingAction = MissingMappingAction.Error;
797
798                         DataTableMapping tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction (TableMappings, srcTable, srcTable, mappingAction);
799
800                         DataTable dataTable = dataSet.Tables [tableMapping.DataSetTable];
801                         if (dataTable == null)
802                                 throw new ArgumentException (String.Format ("Missing table {0}",
803                                                                             srcTable));
804
805                         /** Copied from another Update function **/
806                         if (tableMapping != null) {
807                                 foreach (DataColumn col in dataTable.Columns) {
808                                         if (tableMapping.ColumnMappings.IndexOf (col.ColumnName) >= 0)
809                                                 continue;
810                                         DataColumnMapping columnMapping = DataColumnMappingCollection.GetColumnMappingBySchemaAction (tableMapping.ColumnMappings, col.ColumnName, MissingMappingAction);
811                                         if (columnMapping == null)
812                                                 columnMapping = new DataColumnMapping (col.ColumnName, col.ColumnName);
813                                         tableMapping.ColumnMappings.Add (columnMapping);
814                                 }
815                         } else {
816                                 ArrayList cmc = new ArrayList ();
817                                 foreach (DataColumn col in dataTable.Columns)
818                                         cmc.Add (new DataColumnMapping (col.ColumnName, col.ColumnName));
819                                 tableMapping =
820                                         new DataTableMapping (
821                                                               dataTable.TableName,
822                                                               dataTable.TableName,
823                                                               cmc.ToArray (typeof (DataColumnMapping)) as DataColumnMapping []);
824                         }
825                         /**end insert from another update**/
826                         return Update (dataTable, tableMapping);
827                 }
828
829                 // All the batch methods, should be implemented, if supported,
830                 // by individual providers
831
832                 protected virtual int AddToBatch (IDbCommand command)
833                 {
834                         throw CreateMethodNotSupportedException ();
835                 }
836
837                 protected virtual void ClearBatch ()
838                 {
839                         throw CreateMethodNotSupportedException ();
840                 }
841
842                 protected virtual int ExecuteBatch ()
843                 {
844                         throw CreateMethodNotSupportedException ();
845                 }
846
847                 protected virtual IDataParameter GetBatchedParameter (int commandIdentifier, int parameterIndex)
848                 {
849                         throw CreateMethodNotSupportedException ();
850                 }
851
852                 protected virtual bool GetBatchedRecordsAffected (int commandIdentifier, out int recordsAffected, out Exception error)
853                 {
854                         recordsAffected = 1;
855                         error = null;
856                         return true;
857                 }
858
859                 protected virtual void InitializeBatching ()
860                 {
861                         throw CreateMethodNotSupportedException ();
862                 }
863
864                 protected virtual void TerminateBatching ()
865                 {
866                         throw CreateMethodNotSupportedException ();
867                 }
868
869                 Exception CreateMethodNotSupportedException ()
870                 {
871                         return new NotSupportedException ("Method is not supported.");
872                 }
873                 #endregion // Methods
874         }
875 }