DbDataAdapter.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876
  1. //
  2. // System.Data.Common.DbDataAdapter.cs
  3. //
  4. // Author:
  5. // Rodrigo Moya ([email protected])
  6. // Tim Coleman ([email protected])
  7. //
  8. // (C) Ximian, Inc
  9. // Copyright (C) Tim Coleman, 2002-2003
  10. //
  11. //
  12. // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
  13. //
  14. // Permission is hereby granted, free of charge, to any person obtaining
  15. // a copy of this software and associated documentation files (the
  16. // "Software"), to deal in the Software without restriction, including
  17. // without limitation the rights to use, copy, modify, merge, publish,
  18. // distribute, sublicense, and/or sell copies of the Software, and to
  19. // permit persons to whom the Software is furnished to do so, subject to
  20. // the following conditions:
  21. //
  22. // The above copyright notice and this permission notice shall be
  23. // included in all copies or substantial portions of the Software.
  24. //
  25. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  26. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  27. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  28. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  29. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  30. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  31. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  32. //
  33. using System;
  34. using System.Collections;
  35. using System.ComponentModel;
  36. using System.Data;
  37. using System.Runtime.InteropServices;
  38. namespace System.Data.Common {
  39. public abstract class DbDataAdapter : DataAdapter, ICloneable
  40. {
  41. #region Fields
  42. public const string DefaultSourceTableName = "Table";
  43. const string DefaultSourceColumnName = "Column";
  44. #endregion // Fields
  45. #region Constructors
  46. protected DbDataAdapter()
  47. {
  48. }
  49. [MonoTODO]
  50. protected DbDataAdapter(DbDataAdapter adapter) : base(adapter)
  51. {
  52. }
  53. #endregion // Fields
  54. #region Properties
  55. #if NET_2_0
  56. [MonoTODO]
  57. protected virtual IDbConnection BaseConnection {
  58. get { throw new NotImplementedException (); }
  59. set { throw new NotImplementedException (); }
  60. }
  61. public IDbConnection Connection {
  62. get { return BaseConnection; }
  63. set { BaseConnection = value; }
  64. }
  65. #endif
  66. IDbCommand DeleteCommand {
  67. get { return ((IDbDataAdapter) this).DeleteCommand; }
  68. }
  69. #if NET_2_0
  70. protected internal CommandBehavior FillCommandBehavior {
  71. get { throw new NotImplementedException (); }
  72. set { throw new NotImplementedException (); }
  73. }
  74. #endif
  75. IDbCommand InsertCommand {
  76. get { return ((IDbDataAdapter) this).InsertCommand; }
  77. }
  78. #if NET_2_0
  79. [MonoTODO]
  80. protected virtual IDbCommand this [[Optional] StatementType statementType] {
  81. get { throw new NotImplementedException (); }
  82. set { throw new NotImplementedException (); }
  83. }
  84. protected virtual DbProviderFactory ProviderFactory {
  85. get { throw new NotImplementedException (); }
  86. }
  87. #endif
  88. IDbCommand SelectCommand {
  89. get { return ((IDbDataAdapter) this).SelectCommand; }
  90. }
  91. #if NET_2_0
  92. [MonoTODO]
  93. public IDbTransaction Transaction {
  94. get { throw new NotImplementedException (); }
  95. set { throw new NotImplementedException (); }
  96. }
  97. [MonoTODO]
  98. public int UpdateBatchSize {
  99. get { throw new NotImplementedException (); }
  100. set { throw new NotImplementedException (); }
  101. }
  102. #endif
  103. IDbCommand UpdateCommand {
  104. get { return ((IDbDataAdapter) this).UpdateCommand; }
  105. }
  106. #endregion // Properties
  107. #region Events
  108. #if ONLY_1_0 || ONLY_1_1
  109. [DataCategory ("Fill")]
  110. [DataSysDescription ("Event triggered when a recoverable error occurs during Fill.")]
  111. public event FillErrorEventHandler FillError;
  112. #endif
  113. #endregion // Events
  114. #region Methods
  115. #if NET_2_0
  116. [MonoTODO]
  117. public virtual void BeginInit ()
  118. {
  119. throw new NotImplementedException ();
  120. }
  121. #endif
  122. protected abstract RowUpdatedEventArgs CreateRowUpdatedEvent (DataRow dataRow, IDbCommand command, StatementType statementType, DataTableMapping tableMapping);
  123. protected abstract RowUpdatingEventArgs CreateRowUpdatingEvent (DataRow dataRow, IDbCommand command, StatementType statementType, DataTableMapping tableMapping);
  124. private FillErrorEventArgs CreateFillErrorEvent (DataTable dataTable, object[] values, Exception e)
  125. {
  126. FillErrorEventArgs args = new FillErrorEventArgs (dataTable, values);
  127. args.Errors = e;
  128. args.Continue = false;
  129. return args;
  130. }
  131. protected override void Dispose (bool disposing)
  132. {
  133. if (disposing) {
  134. IDbDataAdapter da = (IDbDataAdapter) this;
  135. if (da.SelectCommand != null) {
  136. da.SelectCommand.Dispose();
  137. da.SelectCommand = null;
  138. }
  139. if (da.InsertCommand != null) {
  140. da.InsertCommand.Dispose();
  141. da.InsertCommand = null;
  142. }
  143. if (da.UpdateCommand != null) {
  144. da.UpdateCommand.Dispose();
  145. da.UpdateCommand = null;
  146. }
  147. if (da.DeleteCommand != null) {
  148. da.DeleteCommand.Dispose();
  149. da.DeleteCommand = null;
  150. }
  151. }
  152. }
  153. #if NET_2_0
  154. [MonoTODO]
  155. public virtual void EndInit ()
  156. {
  157. throw new NotImplementedException ();
  158. }
  159. #endif
  160. public override int Fill (DataSet dataSet)
  161. {
  162. return Fill (dataSet, 0, 0, DefaultSourceTableName, SelectCommand, CommandBehavior.Default);
  163. }
  164. public int Fill (DataTable dataTable)
  165. {
  166. if (dataTable == null)
  167. throw new NullReferenceException ();
  168. return Fill (dataTable, SelectCommand, CommandBehavior.Default);
  169. }
  170. public int Fill (DataSet dataSet, string srcTable)
  171. {
  172. return Fill (dataSet, 0, 0, srcTable, SelectCommand, CommandBehavior.Default);
  173. }
  174. #if NET_2_0
  175. protected override int Fill (DataTable dataTable, IDataReader dataReader)
  176. #else
  177. protected virtual int Fill (DataTable dataTable, IDataReader dataReader)
  178. #endif
  179. {
  180. if (dataReader.FieldCount == 0) {
  181. dataReader.Close ();
  182. return 0;
  183. }
  184. int count = 0;
  185. try {
  186. string tableName = SetupSchema (SchemaType.Mapped, dataTable.TableName);
  187. if (tableName != null) {
  188. dataTable.TableName = tableName;
  189. FillTable (dataTable, dataReader, 0, 0, ref count);
  190. }
  191. } finally {
  192. dataReader.Close ();
  193. }
  194. return count;
  195. }
  196. protected virtual int Fill (DataTable dataTable, IDbCommand command, CommandBehavior behavior)
  197. {
  198. CommandBehavior commandBehavior = behavior;
  199. // first see that the connection is not close.
  200. if (command.Connection.State == ConnectionState.Closed)
  201. {
  202. command.Connection.Open ();
  203. commandBehavior |= CommandBehavior.CloseConnection;
  204. }
  205. return Fill (dataTable, command.ExecuteReader (commandBehavior));
  206. }
  207. #if NET_2_0
  208. [MonoTODO]
  209. public int Fill (int startRecord, int maxRecords, DataTable[] dataTables)
  210. {
  211. throw new NotImplementedException ();
  212. }
  213. #endif
  214. public int Fill (DataSet dataSet, int startRecord, int maxRecords, string srcTable)
  215. {
  216. return this.Fill (dataSet, startRecord, maxRecords, srcTable, SelectCommand, CommandBehavior.Default);
  217. }
  218. #if NET_2_0
  219. [MonoTODO]
  220. protected virtual int Fill (DataTable[] dataTables, int startRecord, int maxRecords, IDbCommand command, CommandBehavior behavior)
  221. {
  222. throw new NotImplementedException ();
  223. }
  224. #endif
  225. #if NET_2_0
  226. protected override int Fill (DataSet dataSet, string srcTable, IDataReader dataReader, int startRecord, int maxRecords)
  227. #else
  228. protected virtual int Fill (DataSet dataSet, string srcTable, IDataReader dataReader, int startRecord, int maxRecords)
  229. #endif
  230. {
  231. if (startRecord < 0)
  232. throw new ArgumentException ("The startRecord parameter was less than 0.");
  233. if (maxRecords < 0)
  234. throw new ArgumentException ("The maxRecords parameter was less than 0.");
  235. DataTable dataTable;
  236. int resultIndex = 0;
  237. int count = 0;
  238. try {
  239. string tableName = srcTable;
  240. do {
  241. // Non-resultset queries like insert, delete or update aren't processed.
  242. if (dataReader.FieldCount != -1)
  243. {
  244. tableName = SetupSchema (SchemaType.Mapped, tableName);
  245. if (tableName != null) {
  246. // check if the table exists in the dataset
  247. if (dataSet.Tables.Contains (tableName))
  248. // get the table from the dataset
  249. dataTable = dataSet.Tables [tableName];
  250. else {
  251. dataTable = new DataTable(tableName);
  252. dataSet.Tables.Add (dataTable);
  253. }
  254. if (!FillTable (dataTable, dataReader, startRecord, maxRecords, ref count)) {
  255. continue;
  256. }
  257. tableName = String.Format ("{0}{1}", srcTable, ++resultIndex);
  258. startRecord = 0;
  259. maxRecords = 0;
  260. }
  261. }
  262. } while (dataReader.NextResult ());
  263. }
  264. finally {
  265. dataReader.Close ();
  266. }
  267. return count;
  268. }
  269. protected virtual int Fill (DataSet dataSet, int startRecord, int maxRecords, string srcTable, IDbCommand command, CommandBehavior behavior)
  270. {
  271. if (MissingSchemaAction == MissingSchemaAction.AddWithKey)
  272. behavior |= CommandBehavior.KeyInfo;
  273. CommandBehavior commandBehavior = behavior;
  274. if (command.Connection.State == ConnectionState.Closed) {
  275. command.Connection.Open ();
  276. commandBehavior |= CommandBehavior.CloseConnection;
  277. }
  278. return Fill (dataSet, srcTable, command.ExecuteReader (commandBehavior), startRecord, maxRecords);
  279. }
  280. private bool FillTable (DataTable dataTable, IDataReader dataReader, int startRecord, int maxRecords, ref int counter)
  281. {
  282. if (dataReader.FieldCount == 0) {
  283. return false;
  284. }
  285. int counterStart = counter;
  286. int[] mapping = BuildSchema (dataReader, dataTable, SchemaType.Mapped);
  287. for (int i = 0; i < startRecord; i++) {
  288. dataReader.Read ();
  289. }
  290. while (dataReader.Read () && (maxRecords == 0 || (counter - counterStart) < maxRecords)) {
  291. try {
  292. dataTable.BeginLoadData ();
  293. dataTable.LoadDataRow (dataReader, mapping, AcceptChangesDuringFill);
  294. dataTable.EndLoadData ();
  295. counter++;
  296. }
  297. catch (Exception e) {
  298. object[] readerArray = new object[dataReader.FieldCount];
  299. object[] tableArray = new object[mapping.Length];
  300. // we get the values from the datareader
  301. dataReader.GetValues (readerArray);
  302. // copy from datareader columns to table columns according to given mapping
  303. for (int i = 0; i < mapping.Length; i++) {
  304. tableArray[i] = readerArray[mapping[i]];
  305. }
  306. FillErrorEventArgs args = CreateFillErrorEvent (dataTable, tableArray, e);
  307. OnFillError (args);
  308. if(!args.Continue) {
  309. return false;
  310. }
  311. }
  312. }
  313. return true;
  314. }
  315. public override DataTable[] FillSchema (DataSet dataSet, SchemaType schemaType)
  316. {
  317. return FillSchema (dataSet, schemaType, SelectCommand, DefaultSourceTableName, CommandBehavior.Default);
  318. }
  319. public DataTable FillSchema (DataTable dataTable, SchemaType schemaType)
  320. {
  321. return FillSchema (dataTable, schemaType, SelectCommand, CommandBehavior.Default);
  322. }
  323. public DataTable[] FillSchema (DataSet dataSet, SchemaType schemaType, string srcTable)
  324. {
  325. return FillSchema (dataSet, schemaType, SelectCommand, srcTable, CommandBehavior.Default);
  326. }
  327. [MonoTODO ("Verify")]
  328. protected virtual DataTable FillSchema (DataTable dataTable, SchemaType schemaType, IDbCommand command, CommandBehavior behavior)
  329. {
  330. behavior |= CommandBehavior.SchemaOnly | CommandBehavior.KeyInfo;
  331. if (command.Connection.State == ConnectionState.Closed) {
  332. command.Connection.Open ();
  333. behavior |= CommandBehavior.CloseConnection;
  334. }
  335. IDataReader reader = command.ExecuteReader (behavior);
  336. try
  337. {
  338. string tableName = SetupSchema (schemaType, dataTable.TableName);
  339. if (tableName != null)
  340. {
  341. BuildSchema (reader, dataTable, schemaType);
  342. }
  343. }
  344. finally
  345. {
  346. reader.Close ();
  347. }
  348. return dataTable;
  349. }
  350. [MonoTODO ("Verify")]
  351. protected virtual DataTable[] FillSchema (DataSet dataSet, SchemaType schemaType, IDbCommand command, string srcTable, CommandBehavior behavior)
  352. {
  353. behavior |= CommandBehavior.SchemaOnly | CommandBehavior.KeyInfo;
  354. if (command.Connection.State == ConnectionState.Closed) {
  355. command.Connection.Open ();
  356. behavior |= CommandBehavior.CloseConnection;
  357. }
  358. IDataReader reader = command.ExecuteReader (behavior);
  359. ArrayList output = new ArrayList ();
  360. string tableName = srcTable;
  361. int index = 0;
  362. DataTable table;
  363. try
  364. {
  365. tableName = SetupSchema (schemaType, tableName);
  366. if (tableName != null)
  367. {
  368. if (dataSet.Tables.Contains (tableName))
  369. table = dataSet.Tables [tableName];
  370. else
  371. {
  372. table = new DataTable(tableName);
  373. dataSet.Tables.Add (table);
  374. }
  375. BuildSchema (reader, table, schemaType);
  376. output.Add (table);
  377. tableName = String.Format ("{0}{1}", srcTable, ++index);
  378. }
  379. }
  380. finally
  381. {
  382. reader.Close ();
  383. }
  384. return (DataTable[]) output.ToArray (typeof (DataTable));
  385. }
  386. #if NET_2_0
  387. [MonoTODO]
  388. public DataSet GetDataSet ()
  389. {
  390. throw new NotImplementedException ();
  391. }
  392. [MonoTODO]
  393. public DataTable GetDataTable ()
  394. {
  395. throw new NotImplementedException ();
  396. }
  397. #endif
  398. private string SetupSchema (SchemaType schemaType, string sourceTableName)
  399. {
  400. DataTableMapping tableMapping = null;
  401. if (schemaType == SchemaType.Mapped)
  402. {
  403. tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction (TableMappings, sourceTableName, sourceTableName, MissingMappingAction);
  404. if (tableMapping != null)
  405. return tableMapping.DataSetTable;
  406. return null;
  407. }
  408. else
  409. return sourceTableName;
  410. }
  411. [EditorBrowsable (EditorBrowsableState.Advanced)]
  412. public override IDataParameter[] GetFillParameters ()
  413. {
  414. IDataParameter[] parameters = new IDataParameter[SelectCommand.Parameters.Count];
  415. SelectCommand.Parameters.CopyTo (parameters, 0);
  416. return parameters;
  417. }
  418. // this method builds the schema for a given datatable. it returns a int array with
  419. // "array[ordinal of datatable column] == index of source column in data reader".
  420. // each column in the datatable has a mapping to a specific column in the datareader,
  421. // the int array represents this match.
  422. [MonoTODO ("Test")]
  423. private int[] BuildSchema (IDataReader reader, DataTable table, SchemaType schemaType)
  424. {
  425. int readerIndex = 0;
  426. int[] mapping = new int[reader.FieldCount]; // mapping the reader indexes to the datatable indexes
  427. ArrayList primaryKey = new ArrayList ();
  428. ArrayList sourceColumns = new ArrayList ();
  429. foreach (DataRow schemaRow in reader.GetSchemaTable ().Rows) {
  430. // generate a unique column name in the source table.
  431. string sourceColumnName;
  432. if (schemaRow.IsNull("ColumnName"))
  433. sourceColumnName = DefaultSourceColumnName;
  434. else
  435. sourceColumnName = (string) schemaRow ["ColumnName"];
  436. string realSourceColumnName = sourceColumnName;
  437. for (int i = 1; sourceColumns.Contains (realSourceColumnName); i += 1)
  438. realSourceColumnName = String.Format ("{0}{1}", sourceColumnName, i);
  439. sourceColumns.Add(realSourceColumnName);
  440. // generate DataSetColumnName from DataTableMapping, if any
  441. string dsColumnName = realSourceColumnName;
  442. DataTableMapping tableMapping = null;
  443. tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction (TableMappings, table.TableName, table.TableName, MissingMappingAction);
  444. if (tableMapping != null)
  445. {
  446. table.TableName = tableMapping.DataSetTable;
  447. // check to see if the column mapping exists
  448. DataColumnMapping columnMapping = DataColumnMappingCollection.GetColumnMappingBySchemaAction(tableMapping.ColumnMappings, realSourceColumnName, MissingMappingAction);
  449. if (columnMapping != null)
  450. {
  451. DataColumn col =
  452. columnMapping.GetDataColumnBySchemaAction(
  453. table ,
  454. (Type)schemaRow["DataType"],
  455. MissingSchemaAction);
  456. if (col != null)
  457. {
  458. // if the column is not in the table - add it.
  459. if (table.Columns.IndexOf(col) == -1)
  460. {
  461. if (MissingSchemaAction == MissingSchemaAction.Add
  462. || MissingSchemaAction == MissingSchemaAction.AddWithKey)
  463. table.Columns.Add(col);
  464. }
  465. if (MissingSchemaAction == MissingSchemaAction.AddWithKey) {
  466. if (!schemaRow["IsKey"].Equals (DBNull.Value))
  467. if ((bool) (schemaRow ["IsKey"]))
  468. primaryKey.Add (col);
  469. col.AutoIncrement = (bool) schemaRow ["IsAutoIncrement"];
  470. }
  471. // add the ordinal of the column as a key and the index of the column in the datareader as a value.
  472. mapping[col.Ordinal] = readerIndex;
  473. }
  474. }
  475. }
  476. readerIndex++;
  477. }
  478. if (primaryKey.Count > 0)
  479. table.PrimaryKey = (DataColumn[])(primaryKey.ToArray(typeof (DataColumn)));
  480. return mapping;
  481. }
  482. [MonoTODO]
  483. object ICloneable.Clone ()
  484. {
  485. throw new NotImplementedException ();
  486. }
  487. [MonoTODO]
  488. public int Update (DataRow[] dataRows)
  489. {
  490. if (dataRows == null)
  491. throw new ArgumentNullException("dataRows");
  492. if (dataRows.Length == 0)
  493. return 0;
  494. if (dataRows[0] == null)
  495. throw new ArgumentException("dataRows[0].");
  496. DataTable table = dataRows[0].Table;
  497. if (table == null)
  498. throw new ArgumentException("table is null reference.");
  499. // all rows must be in the same table
  500. for (int i = 0; i < dataRows.Length; i++)
  501. {
  502. if (dataRows[i] == null)
  503. throw new ArgumentException("dataRows[" + i + "].");
  504. if (dataRows[i].Table != table)
  505. throw new ArgumentException(
  506. " DataRow["
  507. + i
  508. + "] is from a different DataTable than DataRow[0].");
  509. }
  510. // get table mapping for this rows
  511. DataTableMapping tableMapping = TableMappings.GetByDataSetTable(table.TableName);
  512. if (tableMapping == null)
  513. {
  514. tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction(
  515. TableMappings,
  516. table.TableName,
  517. table.TableName,
  518. MissingMappingAction);
  519. if (tableMapping != null) {
  520. foreach (DataColumn col in table.Columns) {
  521. if (tableMapping.ColumnMappings.IndexOf (col.ColumnName) >= 0)
  522. continue;
  523. DataColumnMapping columnMapping = DataColumnMappingCollection.GetColumnMappingBySchemaAction (tableMapping.ColumnMappings, col.ColumnName, MissingMappingAction);
  524. if (columnMapping == null)
  525. columnMapping = new DataColumnMapping (col.ColumnName, col.ColumnName);
  526. tableMapping.ColumnMappings.Add (columnMapping);
  527. }
  528. } else {
  529. ArrayList cmc = new ArrayList ();
  530. foreach (DataColumn col in table.Columns)
  531. cmc.Add (new DataColumnMapping (col.ColumnName, col.ColumnName));
  532. tableMapping =
  533. new DataTableMapping (
  534. table.TableName,
  535. table.TableName,
  536. cmc.ToArray (typeof (DataColumnMapping)) as DataColumnMapping []);
  537. }
  538. }
  539. DataRow[] copy = new DataRow [dataRows.Length];
  540. Array.Copy(dataRows, 0, copy, 0, dataRows.Length);
  541. return Update(copy, tableMapping);
  542. }
  543. public override int Update (DataSet dataSet)
  544. {
  545. return Update (dataSet, DefaultSourceTableName);
  546. }
  547. public int Update (DataTable dataTable)
  548. {
  549. /*
  550. int index = TableMappings.IndexOfDataSetTable (dataTable.TableName);
  551. if (index < 0)
  552. throw new ArgumentException ();
  553. return Update (dataTable, TableMappings [index]);
  554. */
  555. DataTableMapping tableMapping = TableMappings.GetByDataSetTable (dataTable.TableName);
  556. if (tableMapping == null)
  557. {
  558. tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction (
  559. TableMappings,
  560. dataTable.TableName,
  561. dataTable.TableName,
  562. MissingMappingAction);
  563. if (tableMapping != null) {
  564. foreach (DataColumn col in dataTable.Columns) {
  565. if (tableMapping.ColumnMappings.IndexOf (col.ColumnName) >= 0)
  566. continue;
  567. DataColumnMapping columnMapping = DataColumnMappingCollection.GetColumnMappingBySchemaAction (tableMapping.ColumnMappings, col.ColumnName, MissingMappingAction);
  568. if (columnMapping == null)
  569. columnMapping = new DataColumnMapping (col.ColumnName, col.ColumnName);
  570. tableMapping.ColumnMappings.Add (columnMapping);
  571. }
  572. } else {
  573. ArrayList cmc = new ArrayList ();
  574. foreach (DataColumn col in dataTable.Columns)
  575. cmc.Add (new DataColumnMapping (col.ColumnName, col.ColumnName));
  576. tableMapping =
  577. new DataTableMapping (
  578. dataTable.TableName,
  579. dataTable.TableName,
  580. cmc.ToArray (typeof (DataColumnMapping)) as DataColumnMapping []);
  581. }
  582. }
  583. return Update (dataTable, tableMapping);
  584. }
  585. private int Update (DataTable dataTable, DataTableMapping tableMapping)
  586. {
  587. DataRow[] rows = new DataRow [dataTable.Rows.Count];
  588. dataTable.Rows.CopyTo (rows, 0);
  589. return Update (rows, tableMapping);
  590. }
  591. [MonoTODO]
  592. protected virtual int Update (DataRow[] dataRows, DataTableMapping tableMapping)
  593. {
  594. int updateCount = 0;
  595. foreach (DataRow row in dataRows) {
  596. StatementType statementType = StatementType.Update;
  597. IDbCommand command = null;
  598. string commandName = String.Empty;
  599. bool useCommandBuilder = false;
  600. switch (row.RowState) {
  601. case DataRowState.Added:
  602. statementType = StatementType.Insert;
  603. command = InsertCommand;
  604. commandName = "Insert";
  605. break;
  606. case DataRowState.Deleted:
  607. statementType = StatementType.Delete;
  608. command = DeleteCommand;
  609. commandName = "Delete";
  610. break;
  611. case DataRowState.Modified:
  612. statementType = StatementType.Update;
  613. command = UpdateCommand;
  614. commandName = "Update";
  615. break;
  616. case DataRowState.Unchanged:
  617. continue;
  618. case DataRowState.Detached:
  619. throw new NotImplementedException ();
  620. }
  621. if (command == null)
  622. useCommandBuilder = true;
  623. RowUpdatingEventArgs updatingArgs = CreateRowUpdatingEvent (row, command, statementType, tableMapping);
  624. OnRowUpdating (updatingArgs);
  625. if (updatingArgs.Status == UpdateStatus.ErrorsOccurred)
  626. throw (updatingArgs.Errors);
  627. if (command == null && updatingArgs.Command != null)
  628. command = updatingArgs.Command;
  629. else if (command == null)
  630. throw new InvalidOperationException (String.Format ("Update requires a valid {0}Command when passed a DataRow collection with modified rows.", commandName));
  631. if (!useCommandBuilder) {
  632. DataColumnMappingCollection columnMappings = tableMapping.ColumnMappings;
  633. foreach (IDataParameter parameter in command.Parameters) {
  634. string dsColumnName = parameter.SourceColumn;
  635. if (columnMappings.Contains(parameter.SourceColumn))
  636. dsColumnName = columnMappings [parameter.SourceColumn].DataSetColumn;
  637. DataRowVersion rowVersion = DataRowVersion.Default;
  638. // Parameter version is ignored for non-update commands
  639. if (statementType == StatementType.Update)
  640. rowVersion = parameter.SourceVersion;
  641. if (statementType == StatementType.Delete)
  642. rowVersion = DataRowVersion.Original;
  643. parameter.Value = row [dsColumnName, rowVersion];
  644. }
  645. }
  646. CommandBehavior commandBehavior = CommandBehavior.Default;
  647. if (command.Connection.State == ConnectionState.Closed)
  648. {
  649. command.Connection.Open ();
  650. commandBehavior |= CommandBehavior.CloseConnection;
  651. }
  652. IDataReader reader = null;
  653. try
  654. {
  655. // use ExecuteReader because we want to use the commandbehavior parameter.
  656. // so the connection will be closed if needed.
  657. reader = command.ExecuteReader (commandBehavior);
  658. // update the current row, if the update command returns any resultset
  659. // ignore other than the first record.
  660. DataColumnMappingCollection columnMappings = tableMapping.ColumnMappings;
  661. if (command.UpdatedRowSource == UpdateRowSource.Both ||
  662. command.UpdatedRowSource == UpdateRowSource.FirstReturnedRecord) {
  663. if (reader.Read ()){
  664. DataTable retSchema = reader.GetSchemaTable ();
  665. foreach (DataRow dr in retSchema.Rows) {
  666. string columnName = dr ["ColumnName"].ToString ();
  667. string dstColumnName = columnName;
  668. if (columnMappings != null &&
  669. columnMappings.Contains(columnName))
  670. dstColumnName = columnMappings [dstColumnName].DataSetColumn;
  671. try {
  672. row [dstColumnName] = reader [columnName];
  673. }catch (Exception) {} // column is not available here
  674. }
  675. }
  676. }
  677. reader.Close ();
  678. int tmp = reader.RecordsAffected; // records affected is valid only after closing reader
  679. // if the execute does not effect any rows we throw an exception.
  680. if (tmp == 0)
  681. throw new DBConcurrencyException("Concurrency violation: the " +
  682. commandName +"Command affected 0 records.");
  683. updateCount += tmp;
  684. if (command.UpdatedRowSource == UpdateRowSource.Both ||
  685. command.UpdatedRowSource == UpdateRowSource.OutputParameters) {
  686. // Update output parameters to row values
  687. foreach (IDataParameter parameter in command.Parameters) {
  688. if (parameter.Direction != ParameterDirection.InputOutput
  689. && parameter.Direction != ParameterDirection.Output
  690. && parameter.Direction != ParameterDirection.ReturnValue)
  691. continue;
  692. string dsColumnName = parameter.SourceColumn;
  693. if (columnMappings != null &&
  694. columnMappings.Contains(parameter.SourceColumn))
  695. dsColumnName = columnMappings [parameter.SourceColumn].DataSetColumn;
  696. row [dsColumnName] = parameter.Value;
  697. }
  698. }
  699. RowUpdatedEventArgs updatedArgs = CreateRowUpdatedEvent(row, command, statementType, tableMapping);
  700. OnRowUpdated(updatedArgs);
  701. switch(updatedArgs.Status) {
  702. case UpdateStatus.Continue:
  703. row.AcceptChanges();
  704. break;
  705. case UpdateStatus.ErrorsOccurred:
  706. throw(updatedArgs.Errors);
  707. case UpdateStatus.SkipCurrentRow:
  708. continue;
  709. case UpdateStatus.SkipAllRemainingRows:
  710. row.AcceptChanges ();
  711. return updateCount;
  712. }
  713. row.AcceptChanges ();
  714. }
  715. catch (Exception e)
  716. {
  717. if (ContinueUpdateOnError)
  718. row.RowError = e.Message;// do somthing with the error
  719. else
  720. throw e;
  721. }
  722. finally
  723. {
  724. if (reader != null && !reader.IsClosed)
  725. reader.Close ();
  726. }
  727. }
  728. return updateCount;
  729. }
  730. public int Update (DataSet dataSet, string sourceTable)
  731. {
  732. MissingMappingAction mappingAction = MissingMappingAction;
  733. if (mappingAction == MissingMappingAction.Ignore)
  734. mappingAction = MissingMappingAction.Error;
  735. DataTableMapping tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction (TableMappings, sourceTable, sourceTable, mappingAction);
  736. DataTable dataTable = dataSet.Tables[tableMapping.DataSetTable];
  737. if (dataTable == null)
  738. throw new ArgumentException ("sourceTable");
  739. return Update (dataTable, tableMapping);
  740. }
  741. #if ONLY_1_0 || ONLY_1_1
  742. protected virtual void OnFillError (FillErrorEventArgs value)
  743. {
  744. if (FillError != null)
  745. FillError (this, value);
  746. }
  747. #endif
  748. protected abstract void OnRowUpdated (RowUpdatedEventArgs value);
  749. protected abstract void OnRowUpdating (RowUpdatingEventArgs value);
  750. #endregion // Methods
  751. }
  752. }