DbDataAdapter.cs 36 KB

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