2 // System.Data.Common.DbDataAdapter.cs
5 // Rodrigo Moya (rodrigo@ximian.com)
6 // Tim Coleman (tim@timcoleman.com)
7 // Sureshkumar T <tsureshkumar@novell.com>
10 // Copyright (C) Tim Coleman, 2002-2003
14 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
16 // Permission is hereby granted, free of charge, to any person obtaining
17 // a copy of this software and associated documentation files (the
18 // "Software"), to deal in the Software without restriction, including
19 // without limitation the rights to use, copy, modify, merge, publish,
20 // distribute, sublicense, and/or sell copies of the Software, and to
21 // permit persons to whom the Software is furnished to do so, subject to
22 // the following conditions:
24 // The above copyright notice and this permission notice shall be
25 // included in all copies or substantial portions of the Software.
27 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
28 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
29 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
30 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
31 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
32 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
33 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
37 using System.Collections;
38 using System.ComponentModel;
40 using System.Runtime.InteropServices;
42 namespace System.Data.Common {
44 public abstract class DbDataAdapter : DataAdapter, IDbDataAdapter, IDataAdapter, ICloneable
46 public abstract class DbDataAdapter : DataAdapter, ICloneable
51 public const string DefaultSourceTableName = "Table";
52 const string DefaultSourceColumnName = "Column";
55 IDbCommand _selectCommand;
56 IDbCommand _updateCommand;
57 IDbCommand _deleteCommand;
58 IDbCommand _insertCommand;
65 protected DbDataAdapter()
70 protected DbDataAdapter(DbDataAdapter adapter) : base(adapter)
79 protected internal CommandBehavior FillCommandBehavior {
80 get { throw new NotImplementedException (); }
81 set { throw new NotImplementedException (); }
85 IDbCommand IDbDataAdapter.SelectCommand {
86 get { return _selectCommand; }
87 set { _selectCommand = value; }
91 IDbCommand IDbDataAdapter.UpdateCommand{
92 get { return _updateCommand; }
93 set { _updateCommand = value; }
97 IDbCommand IDbDataAdapter.DeleteCommand{
98 get { return _deleteCommand; }
99 set { _deleteCommand = value; }
103 IDbCommand IDbDataAdapter.InsertCommand{
104 get { return _insertCommand; }
105 set { _insertCommand = value; }
110 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
111 public DbCommand SelectCommand {
112 get { return (DbCommand) ((IDbDataAdapter) this).SelectCommand; }
113 set { ((IDbDataAdapter) this).SelectCommand = value; }
118 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
119 public DbCommand DeleteCommand {
120 get { return (DbCommand) ((IDbDataAdapter) this).DeleteCommand; }
121 set { ((IDbDataAdapter) this).DeleteCommand = value; }
126 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
127 public DbCommand InsertCommand {
128 get { return (DbCommand) ((IDbDataAdapter) this).InsertCommand; }
129 set { ((IDbDataAdapter) this).InsertCommand = value; }
134 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
135 public DbCommand UpdateCommand {
136 get { return (DbCommand) ((IDbDataAdapter) this).UpdateCommand; }
137 set { ((IDbDataAdapter) this).UpdateCommand = value; }
142 public virtual int UpdateBatchSize {
144 set { throw new NotSupportedException (); }
147 IDbCommand SelectCommand {
148 get { return ((IDbDataAdapter) this).SelectCommand; }
151 IDbCommand UpdateCommand {
152 get { return ((IDbDataAdapter) this).UpdateCommand; }
155 IDbCommand DeleteCommand {
156 get { return ((IDbDataAdapter) this).DeleteCommand; }
159 IDbCommand InsertCommand {
160 get { return ((IDbDataAdapter) this).InsertCommand; }
164 #endregion // Properties
168 #if ONLY_1_0 || ONLY_1_1
170 [DataCategory ("Fill")]
171 [DataSysDescription ("Event triggered when a recoverable error occurs during Fill.")]
172 public event FillErrorEventHandler FillError;
180 protected virtual RowUpdatedEventArgs CreateRowUpdatedEvent (DataRow dataRow, IDbCommand command,
181 StatementType statementType,
182 DataTableMapping tableMapping)
184 return new RowUpdatedEventArgs (dataRow, command, statementType, tableMapping);
187 protected virtual RowUpdatingEventArgs CreateRowUpdatingEvent (DataRow dataRow, IDbCommand command,
188 StatementType statementType,
189 DataTableMapping tableMapping)
191 return new RowUpdatingEventArgs (dataRow, command, statementType, tableMapping);
195 protected virtual void OnRowUpdated (RowUpdatedEventArgs value)
200 protected virtual void OnRowUpdating (RowUpdatingEventArgs value)
204 protected abstract RowUpdatedEventArgs CreateRowUpdatedEvent (DataRow dataRow, IDbCommand command,
205 StatementType statementType,
206 DataTableMapping tableMapping);
208 protected abstract RowUpdatingEventArgs CreateRowUpdatingEvent (DataRow dataRow, IDbCommand command,
209 StatementType statementType,
210 DataTableMapping tableMapping);
212 protected abstract void OnRowUpdated (RowUpdatedEventArgs value);
213 protected abstract void OnRowUpdating (RowUpdatingEventArgs value);
217 private FillErrorEventArgs CreateFillErrorEvent (DataTable dataTable, object[] values, Exception e)
219 FillErrorEventArgs args = new FillErrorEventArgs (dataTable, values);
221 args.Continue = false;
225 protected override void Dispose (bool disposing)
228 IDbDataAdapter da = (IDbDataAdapter) this;
229 if (da.SelectCommand != null) {
230 da.SelectCommand.Dispose();
231 da.SelectCommand = null;
233 if (da.InsertCommand != null) {
234 da.InsertCommand.Dispose();
235 da.InsertCommand = null;
237 if (da.UpdateCommand != null) {
238 da.UpdateCommand.Dispose();
239 da.UpdateCommand = null;
241 if (da.DeleteCommand != null) {
242 da.DeleteCommand.Dispose();
243 da.DeleteCommand = null;
248 public override int Fill (DataSet dataSet)
250 return Fill (dataSet, 0, 0, DefaultSourceTableName, ((IDbDataAdapter) this).SelectCommand, CommandBehavior.Default);
253 public int Fill (DataTable dataTable)
255 if (dataTable == null)
256 throw new ArgumentNullException ("DataTable");
258 return Fill (dataTable, ((IDbDataAdapter) this).SelectCommand, CommandBehavior.Default);
261 public int Fill (DataSet dataSet, string srcTable)
263 return Fill (dataSet, 0, 0, srcTable, ((IDbDataAdapter) this).SelectCommand, CommandBehavior.Default);
267 [MonoTODO ("This needs to be moved to DataAdapter.For now, just override")]
272 int Fill (DataTable dataTable, IDataReader dataReader)
274 if (dataReader.FieldCount == 0) {
282 string tableName = SetupSchema (SchemaType.Mapped, dataTable.TableName);
283 if (tableName != null) {
284 dataTable.TableName = tableName;
285 FillTable (dataTable, dataReader, 0, 0, ref count);
294 protected virtual int Fill (DataTable dataTable, IDbCommand command, CommandBehavior behavior)
296 CommandBehavior commandBehavior = behavior;
298 // first see that the connection is not close.
299 if (command.Connection.State == ConnectionState.Closed)
301 command.Connection.Open ();
302 commandBehavior |= CommandBehavior.CloseConnection;
304 return Fill (dataTable, command.ExecuteReader (commandBehavior));
307 public int Fill (DataSet dataSet, int startRecord, int maxRecords, string srcTable)
309 return this.Fill (dataSet, startRecord, maxRecords, srcTable, ((IDbDataAdapter) this).SelectCommand, CommandBehavior.Default);
314 public int Fill (int startRecord, int maxRecords, DataTable[] dataTables)
316 throw new NotImplementedException ();
320 protected virtual int Fill (DataTable[] dataTables, int startRecord, int maxRecords, IDbCommand command, CommandBehavior behavior)
322 throw new NotImplementedException ();
328 [MonoTODO ("This needs to be moved to DataAdapter.For now, just override")]
333 int Fill (DataSet dataSet, string srcTable, IDataReader dataReader, int startRecord, int maxRecords)
336 throw new ArgumentNullException ("DataSet");
339 throw new ArgumentException ("The startRecord parameter was less than 0.");
341 throw new ArgumentException ("The maxRecords parameter was less than 0.");
343 DataTable dataTable = null;
348 string tableName = srcTable;
350 // Non-resultset queries like insert, delete or update aren't processed.
351 if (dataReader.FieldCount != -1)
353 tableName = SetupSchema (SchemaType.Mapped, tableName);
354 if (tableName != null) {
356 // check if the table exists in the dataset
357 if (dataSet.Tables.Contains (tableName))
358 // get the table from the dataset
359 dataTable = dataSet.Tables [tableName];
361 // Do not create schema if MissingSchemAction is set to Ignore
362 if (this.MissingSchemaAction == MissingSchemaAction.Ignore)
364 dataTable = dataSet.Tables.Add (tableName);
367 if (!FillTable (dataTable, dataReader, startRecord, maxRecords, ref count)) {
371 tableName = String.Format ("{0}{1}", srcTable, ++resultIndex);
377 } while (dataReader.NextResult ());
386 protected virtual int Fill (DataSet dataSet, int startRecord, int maxRecords, string srcTable, IDbCommand command, CommandBehavior behavior)
388 if (MissingSchemaAction == MissingSchemaAction.AddWithKey)
389 behavior |= CommandBehavior.KeyInfo;
390 CommandBehavior commandBehavior = behavior;
392 if (command.Connection.State == ConnectionState.Closed) {
393 command.Connection.Open ();
394 commandBehavior |= CommandBehavior.CloseConnection;
396 return Fill (dataSet, srcTable, command.ExecuteReader (commandBehavior), startRecord, maxRecords);
399 private bool FillTable (DataTable dataTable, IDataReader dataReader, int startRecord, int maxRecords, ref int counter)
401 if (dataReader.FieldCount == 0)
404 int counterStart = counter;
406 int[] mapping = BuildSchema (dataReader, dataTable, SchemaType.Mapped);
408 int[] sortedMapping = new int[mapping.Length];
409 int length = sortedMapping.Length;
410 for(int i=0; i < sortedMapping.Length; i++) {
412 sortedMapping[mapping[i]] = i;
414 sortedMapping[--length] = i;
417 for (int i = 0; i < startRecord; i++) {
421 dataTable.BeginLoadData ();
422 while (dataReader.Read () && (maxRecords == 0 || (counter - counterStart) < maxRecords)) {
424 dataTable.LoadDataRow (dataReader, sortedMapping, length, AcceptChangesDuringFill);
427 catch (Exception e) {
428 object[] readerArray = new object[dataReader.FieldCount];
429 object[] tableArray = new object[mapping.Length];
430 // we get the values from the datareader
431 dataReader.GetValues (readerArray);
432 // copy from datareader columns to table columns according to given mapping
433 for (int i = 0; i < mapping.Length; i++) {
434 if (mapping[i] >= 0) {
435 tableArray[i] = readerArray[mapping[i]];
438 FillErrorEventArgs args = CreateFillErrorEvent (dataTable, tableArray, e);
441 // if args.Continue is not set to true or if a handler is not set, rethrow the error..
446 dataTable.EndLoadData ();
452 /// Fills the given datatable using values from reader. if a value
453 /// for a column is null, that will be filled with default value.
455 /// <returns>No. of rows affected </returns>
456 internal static int FillFromReader (DataTable table,
461 LoadOption loadOption
464 if (reader.FieldCount == 0)
467 for (int i = 0; i < start; i++)
471 object [] values = new object [mapping.Length];
472 while (reader.Read () &&
473 (length == 0 || counter < length)) {
475 for (int i = 0 ; i < mapping.Length; i++)
476 values [i] = mapping [i] < 0 ? null : reader [mapping [i]];
478 table.BeginLoadData ();
479 table.LoadDataRow (values, loadOption);
480 table.EndLoadData ();
488 public override DataTable[] FillSchema (DataSet dataSet, SchemaType schemaType)
490 return FillSchema (dataSet, schemaType, ((IDbDataAdapter) this).SelectCommand, DefaultSourceTableName, CommandBehavior.Default);
493 public DataTable FillSchema (DataTable dataTable, SchemaType schemaType)
495 return FillSchema (dataTable, schemaType, ((IDbDataAdapter) this).SelectCommand, CommandBehavior.Default);
498 public DataTable[] FillSchema (DataSet dataSet, SchemaType schemaType, string srcTable)
500 return FillSchema (dataSet, schemaType, ((IDbDataAdapter) this).SelectCommand, srcTable, CommandBehavior.Default);
503 [MonoTODO ("Verify")]
504 protected virtual DataTable FillSchema (DataTable dataTable, SchemaType schemaType, IDbCommand command, CommandBehavior behavior)
506 if (dataTable == null)
507 throw new ArgumentNullException ("DataTable");
509 behavior |= CommandBehavior.SchemaOnly | CommandBehavior.KeyInfo;
510 if (command.Connection.State == ConnectionState.Closed) {
511 command.Connection.Open ();
512 behavior |= CommandBehavior.CloseConnection;
515 IDataReader reader = command.ExecuteReader (behavior);
518 string tableName = SetupSchema (schemaType, dataTable.TableName);
519 if (tableName != null)
521 // FillSchema should add the KeyInfo unless MissingSchemaAction
522 // is set to Ignore or Error.
523 MissingSchemaAction schemaAction = MissingSchemaAction;
524 if (!(schemaAction == MissingSchemaAction.Ignore ||
525 schemaAction == MissingSchemaAction.Error))
526 schemaAction = MissingSchemaAction.AddWithKey;
528 BuildSchema (reader, dataTable, schemaType, schemaAction,
529 MissingMappingAction, TableMappings);
539 [MonoTODO ("Verify")]
540 protected virtual DataTable[] FillSchema (DataSet dataSet, SchemaType schemaType, IDbCommand command, string srcTable, CommandBehavior behavior)
543 throw new ArgumentNullException ("DataSet");
545 behavior |= CommandBehavior.SchemaOnly | CommandBehavior.KeyInfo;
546 if (command.Connection.State == ConnectionState.Closed) {
547 command.Connection.Open ();
548 behavior |= CommandBehavior.CloseConnection;
551 IDataReader reader = command.ExecuteReader (behavior);
552 ArrayList output = new ArrayList ();
553 string tableName = srcTable;
558 // FillSchema should add the KeyInfo unless MissingSchemaAction
559 // is set to Ignore or Error.
560 MissingSchemaAction schemaAction = MissingSchemaAction;
561 if (!(MissingSchemaAction == MissingSchemaAction.Ignore ||
562 MissingSchemaAction == MissingSchemaAction.Error))
563 schemaAction = MissingSchemaAction.AddWithKey;
566 tableName = SetupSchema (schemaType, tableName);
567 if (tableName != null)
569 if (dataSet.Tables.Contains (tableName))
570 table = dataSet.Tables [tableName];
573 // Do not create schema if MissingSchemAction is set to Ignore
574 if (this.MissingSchemaAction == MissingSchemaAction.Ignore)
576 table = dataSet.Tables.Add (tableName);
579 BuildSchema (reader, table, schemaType, schemaAction,
580 MissingMappingAction, TableMappings);
582 tableName = String.Format ("{0}{1}", srcTable, ++index);
584 }while (reader.NextResult ());
590 return (DataTable[]) output.ToArray (typeof (DataTable));
593 private string SetupSchema (SchemaType schemaType, string sourceTableName)
595 DataTableMapping tableMapping = null;
597 if (schemaType == SchemaType.Mapped)
599 tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction (TableMappings, sourceTableName, sourceTableName, MissingMappingAction);
600 if (tableMapping != null)
601 return tableMapping.DataSetTable;
605 return sourceTableName;
608 [EditorBrowsable (EditorBrowsableState.Advanced)]
609 public override IDataParameter[] GetFillParameters ()
611 IDataParameter[] parameters = new IDataParameter [SelectCommand.Parameters.Count];
612 SelectCommand.Parameters.CopyTo (parameters, 0);
616 // this method builds the schema for a given datatable. it returns a int array with
617 // "array[ordinal of datatable column] == index of source column in data reader".
618 // each column in the datatable has a mapping to a specific column in the datareader,
619 // the int array represents this match.
621 private int[] BuildSchema (IDataReader reader, DataTable table, SchemaType schemaType)
623 return BuildSchema (reader, table, schemaType, MissingSchemaAction,
624 MissingMappingAction, TableMappings);
628 /// Creates or Modifies the schema of the given DataTable based on the schema of
629 /// the reader and the arguments passed.
631 internal static int[] BuildSchema (IDataReader reader,
633 SchemaType schemaType,
634 MissingSchemaAction missingSchAction,
635 MissingMappingAction missingMapAction,
636 DataTableMappingCollection dtMapping
640 // FIXME : this fails if query has fewer columns than a table
641 int[] mapping = new int[table.Columns.Count]; // mapping the reader indexes to the datatable indexes
643 for(int i=0; i < mapping.Length; i++) {
647 ArrayList primaryKey = new ArrayList ();
648 ArrayList sourceColumns = new ArrayList ();
649 bool createPrimaryKey = true;
651 DataTable schemaTable = reader.GetSchemaTable ();
653 DataColumn ColumnNameCol = schemaTable.Columns["ColumnName"];
654 DataColumn DataTypeCol = schemaTable.Columns["DataType"];
655 DataColumn IsAutoIncrementCol = schemaTable.Columns["IsAutoIncrement"];
656 DataColumn AllowDBNullCol = schemaTable.Columns["AllowDBNull"];
657 DataColumn IsReadOnlyCol = schemaTable.Columns["IsReadOnly"];
658 DataColumn IsKeyCol = schemaTable.Columns["IsKey"];
659 DataColumn IsUniqueCol = schemaTable.Columns["IsUnique"];
660 DataColumn ColumnSizeCol = schemaTable.Columns["ColumnSize"];
662 foreach (DataRow schemaRow in schemaTable.Rows) {
663 // generate a unique column name in the source table.
664 string sourceColumnName;
665 string realSourceColumnName ;
666 if (ColumnNameCol == null || schemaRow.IsNull(ColumnNameCol) || (string)schemaRow [ColumnNameCol] == String.Empty) {
667 sourceColumnName = DefaultSourceColumnName;
668 realSourceColumnName = DefaultSourceColumnName + "1";
671 sourceColumnName = (string) schemaRow [ColumnNameCol];
672 realSourceColumnName = sourceColumnName;
675 for (int i = 1; sourceColumns.Contains (realSourceColumnName); i += 1)
676 realSourceColumnName = String.Format ("{0}{1}", sourceColumnName, i);
677 sourceColumns.Add(realSourceColumnName);
679 // generate DataSetColumnName from DataTableMapping, if any
680 string dsColumnName = realSourceColumnName;
681 DataTableMapping tableMapping = null;
683 //FIXME : The sourcetable name shud get passed as a parameter..
684 int index = dtMapping.IndexOfDataSetTable (table.TableName);
685 string srcTable = (index != -1 ? dtMapping[index].SourceTable : table.TableName);
686 tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction (dtMapping, srcTable, table.TableName, missingMapAction);
687 if (tableMapping != null)
689 table.TableName = tableMapping.DataSetTable;
690 // check to see if the column mapping exists
691 DataColumnMapping columnMapping = DataColumnMappingCollection.GetColumnMappingBySchemaAction(tableMapping.ColumnMappings, realSourceColumnName, missingMapAction);
692 if (columnMapping != null)
694 Type columnType = (Type)schemaRow[DataTypeCol];
696 columnMapping.GetDataColumnBySchemaAction(
703 // if the column is not in the table - add it.
704 if (table.Columns.IndexOf(col) == -1)
706 if (missingSchAction == MissingSchemaAction.Add
707 || missingSchAction == MissingSchemaAction.AddWithKey)
708 table.Columns.Add(col);
710 int[] tmp = new int[mapping.Length + 1];
711 Array.Copy(mapping,0,tmp,0,col.Ordinal);
712 Array.Copy(mapping,col.Ordinal,tmp,col.Ordinal + 1,mapping.Length - col.Ordinal);
717 if (missingSchAction == MissingSchemaAction.AddWithKey) {
719 object value = (AllowDBNullCol != null) ? schemaRow[AllowDBNullCol] : null;
720 bool allowDBNull = value is bool ? (bool)value : true;
722 value = (IsKeyCol != null) ? schemaRow[IsKeyCol] : null;
723 bool isKey = value is bool ? (bool)value : false;
725 value = (IsAutoIncrementCol != null) ? schemaRow[IsAutoIncrementCol] : null;
726 bool isAutoIncrement = value is bool ? (bool)value : false;
728 value = (IsReadOnlyCol != null) ? schemaRow[IsReadOnlyCol] : null;
729 bool isReadOnly = value is bool ? (bool)value : false;
731 value = (IsUniqueCol != null) ? schemaRow[IsUniqueCol] : null;
732 bool isUnique = value is bool ? (bool)value : false;
734 col.AllowDBNull = allowDBNull;
735 // fill woth key info
736 if (isAutoIncrement && DataColumn.CanAutoIncrement(columnType)) {
737 col.AutoIncrement = true;
739 col.AllowDBNull = false;
742 if (columnType == DbTypes.TypeOfString) {
743 col.MaxLength = (ColumnSizeCol != null) ? (int)schemaRow[ColumnSizeCol] : 0;
749 if (!allowDBNull && (!isReadOnly || isKey))
750 col.AllowDBNull = false;
751 if (isUnique && !isKey && !columnType.IsArray) {
754 col.AllowDBNull = false;
757 // This might not be set by all DataProviders
758 bool isHidden = false;
759 if (schemaTable.Columns.Contains ("IsHidden")) {
760 value = schemaRow["IsHidden"];
761 isHidden = ((value is bool) ? (bool)value : false);
764 if (isKey && !isHidden) {
765 primaryKey.Add (col);
767 createPrimaryKey = false;
770 // add the ordinal of the column as a key and the index of the column in the datareader as a value.
771 mapping[col.Ordinal] = readerIndex++;
776 if (primaryKey.Count > 0) {
777 DataColumn[] colKey = (DataColumn[])(primaryKey.ToArray(typeof (DataColumn)));
778 if (createPrimaryKey)
779 table.PrimaryKey = colKey;
781 UniqueConstraint uConstraint = new UniqueConstraint(colKey);
782 for (int i = 0; i < table.Constraints.Count; i++) {
783 if (table.Constraints[i].Equals(uConstraint)) {
789 if (uConstraint != null)
790 table.Constraints.Add(uConstraint);
797 object ICloneable.Clone ()
799 throw new NotImplementedException ();
803 public int Update (DataRow[] dataRows)
805 if (dataRows == null)
806 throw new ArgumentNullException("dataRows");
808 if (dataRows.Length == 0)
811 if (dataRows[0] == null)
812 throw new ArgumentException("dataRows[0].");
814 DataTable table = dataRows[0].Table;
816 throw new ArgumentException("table is null reference.");
818 // all rows must be in the same table
819 for (int i = 0; i < dataRows.Length; i++)
821 if (dataRows[i] == null)
822 throw new ArgumentException("dataRows[" + i + "].");
823 if (dataRows[i].Table != table)
824 throw new ArgumentException(
827 + "] is from a different DataTable than DataRow[0].");
830 // get table mapping for this rows
831 DataTableMapping tableMapping = TableMappings.GetByDataSetTable(table.TableName);
832 if (tableMapping == null)
834 tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction(
838 MissingMappingAction);
839 if (tableMapping != null) {
840 foreach (DataColumn col in table.Columns) {
841 if (tableMapping.ColumnMappings.IndexOf (col.ColumnName) >= 0)
843 DataColumnMapping columnMapping = DataColumnMappingCollection.GetColumnMappingBySchemaAction (tableMapping.ColumnMappings, col.ColumnName, MissingMappingAction);
844 if (columnMapping == null)
845 columnMapping = new DataColumnMapping (col.ColumnName, col.ColumnName);
846 tableMapping.ColumnMappings.Add (columnMapping);
849 ArrayList cmc = new ArrayList ();
850 foreach (DataColumn col in table.Columns)
851 cmc.Add (new DataColumnMapping (col.ColumnName, col.ColumnName));
853 new DataTableMapping (
856 cmc.ToArray (typeof (DataColumnMapping)) as DataColumnMapping []);
860 DataRow[] copy = table.NewRowArray(dataRows.Length);
861 Array.Copy(dataRows, 0, copy, 0, dataRows.Length);
862 return Update(copy, tableMapping);
865 public override int Update (DataSet dataSet)
867 return Update (dataSet, DefaultSourceTableName);
870 public int Update (DataTable dataTable)
873 int index = TableMappings.IndexOfDataSetTable (dataTable.TableName);
875 throw new ArgumentException ();
876 return Update (dataTable, TableMappings [index]);
878 DataTableMapping tableMapping = TableMappings.GetByDataSetTable (dataTable.TableName);
879 if (tableMapping == null)
881 tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction (
885 MissingMappingAction);
886 if (tableMapping != null) {
887 foreach (DataColumn col in dataTable.Columns) {
888 if (tableMapping.ColumnMappings.IndexOf (col.ColumnName) >= 0)
890 DataColumnMapping columnMapping = DataColumnMappingCollection.GetColumnMappingBySchemaAction (tableMapping.ColumnMappings, col.ColumnName, MissingMappingAction);
891 if (columnMapping == null)
892 columnMapping = new DataColumnMapping (col.ColumnName, col.ColumnName);
893 tableMapping.ColumnMappings.Add (columnMapping);
896 ArrayList cmc = new ArrayList ();
897 foreach (DataColumn col in dataTable.Columns)
898 cmc.Add (new DataColumnMapping (col.ColumnName, col.ColumnName));
900 new DataTableMapping (
903 cmc.ToArray (typeof (DataColumnMapping)) as DataColumnMapping []);
906 return Update (dataTable, tableMapping);
909 private int Update (DataTable dataTable, DataTableMapping tableMapping)
911 DataRow[] rows = dataTable.NewRowArray(dataTable.Rows.Count);
912 dataTable.Rows.CopyTo (rows, 0);
913 return Update (rows, tableMapping);
917 protected virtual int Update (DataRow[] dataRows, DataTableMapping tableMapping)
920 foreach (DataRow row in dataRows) {
921 StatementType statementType = StatementType.Update;
922 IDbCommand command = null;
923 string commandName = String.Empty;
925 switch (row.RowState) {
926 case DataRowState.Added:
927 statementType = StatementType.Insert;
928 command = ((IDbDataAdapter) this).InsertCommand;
929 commandName = "Insert";
931 case DataRowState.Deleted:
932 statementType = StatementType.Delete;
933 command = ((IDbDataAdapter) this).DeleteCommand;
934 commandName = "Delete";
936 case DataRowState.Modified:
937 statementType = StatementType.Update;
938 command = ((IDbDataAdapter) this).UpdateCommand;
939 commandName = "Update";
941 case DataRowState.Unchanged:
942 case DataRowState.Detached:
946 RowUpdatingEventArgs argsUpdating = CreateRowUpdatingEvent (row, command, statementType, tableMapping);
948 OnRowUpdating(argsUpdating);
949 switch(argsUpdating.Status) {
950 case UpdateStatus.Continue :
951 //continue in update operation
953 case UpdateStatus.ErrorsOccurred :
954 if (argsUpdating.Errors == null) {
955 argsUpdating.Errors = ExceptionHelper.RowUpdatedError();
957 row.RowError += argsUpdating.Errors.Message;
958 if (!ContinueUpdateOnError) {
959 throw argsUpdating.Errors;
962 case UpdateStatus.SkipAllRemainingRows :
964 case UpdateStatus.SkipCurrentRow :
968 throw ExceptionHelper.InvalidUpdateStatus(argsUpdating.Status);
970 command = argsUpdating.Command;
972 if (command != null) {
973 DataColumnMappingCollection columnMappings = tableMapping.ColumnMappings;
974 IDataParameter nullCheckParam = null;
975 foreach (IDataParameter parameter in command.Parameters) {
976 if ((parameter.Direction & ParameterDirection.Input) != 0) {
977 string dsColumnName = parameter.SourceColumn;
978 if (columnMappings.Contains(parameter.SourceColumn))
979 dsColumnName = columnMappings [parameter.SourceColumn].DataSetColumn;
980 if (dsColumnName == null || dsColumnName.Length <= 0) {
981 nullCheckParam = parameter;
985 DataRowVersion rowVersion = parameter.SourceVersion;
986 // Parameter version is ignored for non-update commands
987 if (statementType == StatementType.Delete)
988 rowVersion = DataRowVersion.Original;
990 parameter.Value = row [dsColumnName, rowVersion];
991 if (nullCheckParam != null && (parameter.Value != null
992 && parameter.Value != DBNull.Value)) {
993 nullCheckParam.Value = 0;
994 nullCheckParam = null;
1000 catch (Exception e) {
1001 argsUpdating.Errors = e;
1002 argsUpdating.Status = UpdateStatus.ErrorsOccurred;
1006 IDataReader reader = null;
1008 if (command == null) {
1009 throw ExceptionHelper.UpdateRequiresCommand(commandName);
1012 CommandBehavior commandBehavior = CommandBehavior.Default;
1013 if (command.Connection.State == ConnectionState.Closed) {
1014 command.Connection.Open ();
1015 commandBehavior |= CommandBehavior.CloseConnection;
1018 // use ExecuteReader because we want to use the commandbehavior parameter.
1019 // so the connection will be closed if needed.
1020 reader = command.ExecuteReader (commandBehavior);
1022 // update the current row, if the update command returns any resultset
1023 // ignore other than the first record.
1024 DataColumnMappingCollection columnMappings = tableMapping.ColumnMappings;
1026 if (command.UpdatedRowSource == UpdateRowSource.Both ||
1027 command.UpdatedRowSource == UpdateRowSource.FirstReturnedRecord) {
1028 if (reader.Read ()){
1029 DataTable retSchema = reader.GetSchemaTable ();
1030 foreach (DataRow dr in retSchema.Rows) {
1031 string columnName = dr ["ColumnName"].ToString ();
1032 string dstColumnName = columnName;
1033 if (columnMappings != null &&
1034 columnMappings.Contains(columnName))
1035 dstColumnName = columnMappings [dstColumnName].DataSetColumn;
1036 DataColumn dstColumn = row.Table.Columns [dstColumnName];
1037 if (dstColumn == null
1038 || (dstColumn.Expression != null
1039 && dstColumn.Expression.Length > 0))
1041 // info from : http://www.error-bank.com/microsoft.public.dotnet.framework.windowsforms.databinding/
1042 // _35_hcsyiv0dha.2328@tk2msftngp10.phx.gbl_Thread.aspx
1043 // disable readonly for non-expression columns.
1044 bool readOnlyState = dstColumn.ReadOnly;
1045 dstColumn.ReadOnly = false;
1047 row [dstColumnName] = reader [columnName];
1049 dstColumn.ReadOnly = readOnlyState;
1056 int tmp = reader.RecordsAffected; // records affected is valid only after closing reader
1057 // if the execute does not effect any rows we throw an exception.
1059 throw new DBConcurrencyException("Concurrency violation: the " +
1060 commandName +"Command affected 0 records.");
1063 if (command.UpdatedRowSource == UpdateRowSource.Both ||
1064 command.UpdatedRowSource == UpdateRowSource.OutputParameters) {
1065 // Update output parameters to row values
1066 foreach (IDataParameter parameter in command.Parameters) {
1067 if (parameter.Direction != ParameterDirection.InputOutput
1068 && parameter.Direction != ParameterDirection.Output
1069 && parameter.Direction != ParameterDirection.ReturnValue)
1072 string dsColumnName = parameter.SourceColumn;
1073 if (columnMappings != null &&
1074 columnMappings.Contains(parameter.SourceColumn))
1075 dsColumnName = columnMappings [parameter.SourceColumn].DataSetColumn;
1076 DataColumn dstColumn = row.Table.Columns [dsColumnName];
1077 if (dstColumn == null
1078 || (dstColumn.Expression != null
1079 && dstColumn.Expression.Length > 0))
1081 bool readOnlyState = dstColumn.ReadOnly;
1082 dstColumn.ReadOnly = false;
1084 row [dsColumnName] = parameter.Value;
1086 dstColumn.ReadOnly = readOnlyState;
1092 RowUpdatedEventArgs updatedArgs = CreateRowUpdatedEvent(row, command, statementType, tableMapping);
1093 OnRowUpdated(updatedArgs);
1094 switch(updatedArgs.Status) {
1095 case UpdateStatus.Continue:
1097 case UpdateStatus.ErrorsOccurred:
1098 if (updatedArgs.Errors == null) {
1099 updatedArgs.Errors = ExceptionHelper.RowUpdatedError();
1101 row.RowError += updatedArgs.Errors.Message;
1102 if (!ContinueUpdateOnError) {
1103 throw updatedArgs.Errors;
1106 case UpdateStatus.SkipCurrentRow:
1108 case UpdateStatus.SkipAllRemainingRows:
1112 if (!AcceptChangesDuringUpdate)
1115 row.AcceptChanges ();
1116 } catch(Exception e) {
1117 row.RowError = e.Message;
1118 if (!ContinueUpdateOnError) {
1122 if (reader != null && ! reader.IsClosed) {
1130 public int Update (DataSet dataSet, string sourceTable)
1132 MissingMappingAction mappingAction = MissingMappingAction;
1134 if (mappingAction == MissingMappingAction.Ignore)
1135 mappingAction = MissingMappingAction.Error;
1137 DataTableMapping tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction (TableMappings, sourceTable, sourceTable, mappingAction);
1139 DataTable dataTable = dataSet.Tables[tableMapping.DataSetTable];
1140 if (dataTable == null)
1141 throw new ArgumentException (String.Format ("Missing table {0}",
1143 return Update (dataTable, tableMapping);
1147 // All the batch methods, should be implemented, if supported,
1148 // by individual providers
1150 protected virtual int AddToBatch (IDbCommand cmd)
1152 throw new NotSupportedException ();
1155 protected virtual void ClearBatch ()
1157 throw new NotSupportedException ();
1160 protected virtual int ExecuteBatch ()
1162 throw new NotSupportedException ();
1165 protected virtual IDataParameter GetBatchedParameter (int commandIdentifier, int parameterIdentifer)
1167 throw new NotSupportedException ();
1170 protected virtual void InitializeBatching ()
1172 throw new NotSupportedException ();
1175 protected virtual void TerminateBatching ()
1177 throw new NotSupportedException ();
1181 #if ONLY_1_0 || ONLY_1_1
1182 protected virtual void OnFillError (FillErrorEventArgs value)
1184 if (FillError != null)
1185 FillError (this, value);
1189 #endregion // Methods