DbDataAdapter.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128
  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. #if NET_2_0
  41. public abstract class DbDataAdapter : DataAdapter, IDbDataAdapter, IDataAdapter, ICloneable
  42. #else
  43. public abstract class DbDataAdapter : DataAdapter, ICloneable
  44. #endif
  45. {
  46. #region Fields
  47. public const string DefaultSourceTableName = "Table";
  48. const string DefaultSourceColumnName = "Column";
  49. #endregion // Fields
  50. #region Constructors
  51. protected DbDataAdapter()
  52. {
  53. }
  54. [MonoTODO]
  55. protected DbDataAdapter(DbDataAdapter adapter) : base(adapter)
  56. {
  57. }
  58. #endregion // Fields
  59. #region Properties
  60. #if NET_2_0
  61. [MonoTODO]
  62. protected virtual IDbConnection BaseConnection {
  63. get { throw new NotImplementedException (); }
  64. set { throw new NotImplementedException (); }
  65. }
  66. public IDbConnection Connection {
  67. get { return BaseConnection; }
  68. set { BaseConnection = value; }
  69. }
  70. #endif
  71. #if NET_2_0
  72. protected internal CommandBehavior FillCommandBehavior {
  73. get { throw new NotImplementedException (); }
  74. set { throw new NotImplementedException (); }
  75. }
  76. #endif
  77. #if NET_2_0
  78. [MonoTODO]
  79. protected virtual IDbCommand this [[Optional] StatementType statementType] {
  80. get { throw new NotImplementedException (); }
  81. set { throw new NotImplementedException (); }
  82. }
  83. [MonoTODO]
  84. protected virtual DbProviderFactory ProviderFactory {
  85. get { throw new NotImplementedException (); }
  86. }
  87. [MonoTODO]
  88. IDbCommand IDbDataAdapter.SelectCommand {
  89. get { return ((IDbDataAdapter) this).SelectCommand; }
  90. set { throw new NotImplementedException(); }
  91. }
  92. [MonoTODO]
  93. IDbCommand IDbDataAdapter.UpdateCommand{
  94. get { return ((IDbDataAdapter) this).UpdateCommand; }
  95. set { throw new NotImplementedException(); }
  96. }
  97. [MonoTODO]
  98. IDbCommand IDbDataAdapter.DeleteCommand{
  99. get { return ((IDbDataAdapter) this).DeleteCommand; }
  100. set { throw new NotImplementedException(); }
  101. }
  102. [MonoTODO]
  103. IDbCommand IDbDataAdapter.InsertCommand{
  104. get { return ((IDbDataAdapter) this).InsertCommand; }
  105. set { throw new NotImplementedException(); }
  106. }
  107. [MonoTODO]
  108. public DbCommand SelectCommand {
  109. get { return (DbCommand) ((IDbDataAdapter) this).SelectCommand; }
  110. set { throw new NotImplementedException(); }
  111. }
  112. [MonoTODO]
  113. public DbCommand DeleteCommand {
  114. get { return (DbCommand) ((IDbDataAdapter) this).DeleteCommand; }
  115. set { throw new NotImplementedException(); }
  116. }
  117. [MonoTODO]
  118. public DbCommand InsertCommand {
  119. get { return (DbCommand) ((IDbDataAdapter) this).InsertCommand; }
  120. set { throw new NotImplementedException(); }
  121. }
  122. [MonoTODO]
  123. public DbCommand UpdateCommand {
  124. get { return (DbCommand) ((IDbDataAdapter) this).UpdateCommand; }
  125. set { throw new NotImplementedException(); }
  126. }
  127. [MonoTODO]
  128. public IDbTransaction Transaction {
  129. get { throw new NotImplementedException (); }
  130. set { throw new NotImplementedException (); }
  131. }
  132. [MonoTODO]
  133. public int UpdateBatchSize {
  134. get { throw new NotImplementedException (); }
  135. set { throw new NotImplementedException (); }
  136. }
  137. #else
  138. IDbCommand SelectCommand {
  139. get { return ((IDbDataAdapter) this).SelectCommand; }
  140. }
  141. IDbCommand UpdateCommand {
  142. get { return ((IDbDataAdapter) this).UpdateCommand; }
  143. }
  144. IDbCommand DeleteCommand {
  145. get { return ((IDbDataAdapter) this).DeleteCommand; }
  146. }
  147. IDbCommand InsertCommand {
  148. get { return ((IDbDataAdapter) this).InsertCommand; }
  149. }
  150. #endif
  151. #endregion // Properties
  152. #region Events
  153. #if ONLY_1_0 || ONLY_1_1
  154. [DataCategory ("Fill")]
  155. [DataSysDescription ("Event triggered when a recoverable error occurs during Fill.")]
  156. public event FillErrorEventHandler FillError;
  157. #endif
  158. #endregion // Events
  159. #region Methods
  160. #if NET_2_0
  161. [MonoTODO]
  162. public virtual void BeginInit ()
  163. {
  164. throw new NotImplementedException ();
  165. }
  166. #endif
  167. protected abstract RowUpdatedEventArgs CreateRowUpdatedEvent (DataRow dataRow, IDbCommand command, StatementType statementType, DataTableMapping tableMapping);
  168. protected abstract RowUpdatingEventArgs CreateRowUpdatingEvent (DataRow dataRow, IDbCommand command, StatementType statementType, DataTableMapping tableMapping);
  169. private FillErrorEventArgs CreateFillErrorEvent (DataTable dataTable, object[] values, Exception e)
  170. {
  171. FillErrorEventArgs args = new FillErrorEventArgs (dataTable, values);
  172. args.Errors = e;
  173. args.Continue = false;
  174. return args;
  175. }
  176. protected override void Dispose (bool disposing)
  177. {
  178. if (disposing) {
  179. IDbDataAdapter da = (IDbDataAdapter) this;
  180. if (da.SelectCommand != null) {
  181. da.SelectCommand.Dispose();
  182. da.SelectCommand = null;
  183. }
  184. if (da.InsertCommand != null) {
  185. da.InsertCommand.Dispose();
  186. da.InsertCommand = null;
  187. }
  188. if (da.UpdateCommand != null) {
  189. da.UpdateCommand.Dispose();
  190. da.UpdateCommand = null;
  191. }
  192. if (da.DeleteCommand != null) {
  193. da.DeleteCommand.Dispose();
  194. da.DeleteCommand = null;
  195. }
  196. }
  197. }
  198. #if NET_2_0
  199. [MonoTODO]
  200. public virtual void EndInit ()
  201. {
  202. throw new NotImplementedException ();
  203. }
  204. #endif
  205. public override int Fill (DataSet dataSet)
  206. {
  207. return Fill (dataSet, 0, 0, DefaultSourceTableName, ((IDbDataAdapter) this).SelectCommand, CommandBehavior.Default);
  208. }
  209. public int Fill (DataTable dataTable)
  210. {
  211. if (dataTable == null)
  212. throw new ArgumentNullException ("DataTable");
  213. return Fill (dataTable, ((IDbDataAdapter) this).SelectCommand, CommandBehavior.Default);
  214. }
  215. public int Fill (DataSet dataSet, string srcTable)
  216. {
  217. return Fill (dataSet, 0, 0, srcTable, ((IDbDataAdapter) this).SelectCommand, CommandBehavior.Default);
  218. }
  219. #if NET_2_0
  220. protected override int Fill (DataTable dataTable, IDataReader dataReader)
  221. #else
  222. protected virtual int Fill (DataTable dataTable, IDataReader dataReader)
  223. #endif
  224. {
  225. if (dataReader.FieldCount == 0) {
  226. dataReader.Close ();
  227. return 0;
  228. }
  229. int count = 0;
  230. try {
  231. string tableName = SetupSchema (SchemaType.Mapped, dataTable.TableName);
  232. if (tableName != null) {
  233. dataTable.TableName = tableName;
  234. FillTable (dataTable, dataReader, 0, 0, ref count);
  235. }
  236. } finally {
  237. dataReader.Close ();
  238. }
  239. return count;
  240. }
  241. protected virtual int Fill (DataTable dataTable, IDbCommand command, CommandBehavior behavior)
  242. {
  243. CommandBehavior commandBehavior = behavior;
  244. // first see that the connection is not close.
  245. if (command.Connection.State == ConnectionState.Closed)
  246. {
  247. command.Connection.Open ();
  248. commandBehavior |= CommandBehavior.CloseConnection;
  249. }
  250. return Fill (dataTable, command.ExecuteReader (commandBehavior));
  251. }
  252. #if NET_2_0
  253. [MonoTODO]
  254. public int Fill (int startRecord, int maxRecords, DataTable[] dataTables)
  255. {
  256. throw new NotImplementedException ();
  257. }
  258. #endif
  259. public int Fill (DataSet dataSet, int startRecord, int maxRecords, string srcTable)
  260. {
  261. return this.Fill (dataSet, startRecord, maxRecords, srcTable, ((IDbDataAdapter) this).SelectCommand, CommandBehavior.Default);
  262. }
  263. #if NET_2_0
  264. [MonoTODO]
  265. protected virtual int Fill (DataTable[] dataTables, int startRecord, int maxRecords, IDbCommand command, CommandBehavior behavior)
  266. {
  267. throw new NotImplementedException ();
  268. }
  269. #endif
  270. #if NET_2_0
  271. protected override int Fill (DataSet dataSet, string srcTable, IDataReader dataReader, int startRecord, int maxRecords)
  272. #else
  273. protected virtual int Fill (DataSet dataSet, string srcTable, IDataReader dataReader, int startRecord, int maxRecords)
  274. #endif
  275. {
  276. if (dataSet == null)
  277. throw new ArgumentNullException ("DataSet");
  278. if (startRecord < 0)
  279. throw new ArgumentException ("The startRecord parameter was less than 0.");
  280. if (maxRecords < 0)
  281. throw new ArgumentException ("The maxRecords parameter was less than 0.");
  282. DataTable dataTable = null;
  283. int resultIndex = 0;
  284. int count = 0;
  285. try {
  286. string tableName = srcTable;
  287. do {
  288. // Non-resultset queries like insert, delete or update aren't processed.
  289. if (dataReader.FieldCount != -1)
  290. {
  291. tableName = SetupSchema (SchemaType.Mapped, tableName);
  292. if (tableName != null) {
  293. // check if the table exists in the dataset
  294. if (dataSet.Tables.Contains (tableName))
  295. // get the table from the dataset
  296. dataTable = dataSet.Tables [tableName];
  297. else {
  298. // Do not create schema if MissingSchemAction is set to Ignore
  299. if (this.MissingSchemaAction == MissingSchemaAction.Ignore)
  300. continue;
  301. dataTable = dataSet.Tables.Add (tableName);
  302. }
  303. if (!FillTable (dataTable, dataReader, startRecord, maxRecords, ref count)) {
  304. continue;
  305. }
  306. tableName = String.Format ("{0}{1}", srcTable, ++resultIndex);
  307. startRecord = 0;
  308. maxRecords = 0;
  309. }
  310. }
  311. } while (dataReader.NextResult ());
  312. }
  313. finally {
  314. dataReader.Close ();
  315. }
  316. return count;
  317. }
  318. protected virtual int Fill (DataSet dataSet, int startRecord, int maxRecords, string srcTable, IDbCommand command, CommandBehavior behavior)
  319. {
  320. if (MissingSchemaAction == MissingSchemaAction.AddWithKey)
  321. behavior |= CommandBehavior.KeyInfo;
  322. CommandBehavior commandBehavior = behavior;
  323. if (command.Connection.State == ConnectionState.Closed) {
  324. command.Connection.Open ();
  325. commandBehavior |= CommandBehavior.CloseConnection;
  326. }
  327. return Fill (dataSet, srcTable, command.ExecuteReader (commandBehavior), startRecord, maxRecords);
  328. }
  329. private bool FillTable (DataTable dataTable, IDataReader dataReader, int startRecord, int maxRecords, ref int counter)
  330. {
  331. if (dataReader.FieldCount == 0)
  332. return false;
  333. int counterStart = counter;
  334. int[] mapping = BuildSchema (dataReader, dataTable, SchemaType.Mapped);
  335. int[] sortedMapping = new int[mapping.Length];
  336. int length = sortedMapping.Length;
  337. for(int i=0; i < sortedMapping.Length; i++) {
  338. if (mapping[i] >= 0)
  339. sortedMapping[mapping[i]] = i;
  340. else
  341. sortedMapping[--length] = i;
  342. }
  343. for (int i = 0; i < startRecord; i++) {
  344. dataReader.Read ();
  345. }
  346. while (dataReader.Read () && (maxRecords == 0 || (counter - counterStart) < maxRecords)) {
  347. try {
  348. dataTable.BeginLoadData ();
  349. dataTable.LoadDataRow (dataReader, sortedMapping, length, AcceptChangesDuringFill);
  350. dataTable.EndLoadData ();
  351. counter++;
  352. }
  353. catch (Exception e) {
  354. object[] readerArray = new object[dataReader.FieldCount];
  355. object[] tableArray = new object[mapping.Length];
  356. // we get the values from the datareader
  357. dataReader.GetValues (readerArray);
  358. // copy from datareader columns to table columns according to given mapping
  359. for (int i = 0; i < mapping.Length; i++) {
  360. if (mapping[i] >= 0) {
  361. tableArray[i] = readerArray[mapping[i]];
  362. }
  363. }
  364. FillErrorEventArgs args = CreateFillErrorEvent (dataTable, tableArray, e);
  365. OnFillError (args);
  366. if(!args.Continue) {
  367. return false;
  368. }
  369. }
  370. }
  371. return true;
  372. }
  373. #if NET_2_0
  374. /// <summary>
  375. /// Fills the given datatable using values from reader. if a value
  376. /// for a column is null, that will be filled with default value.
  377. /// </summary>
  378. /// <returns>No. of rows affected </returns>
  379. internal static int FillFromReader (DataTable table,
  380. IDataReader reader,
  381. int start,
  382. int length,
  383. int [] mapping,
  384. LoadOption loadOption
  385. )
  386. {
  387. if (reader.FieldCount == 0)
  388. return 0 ;
  389. for (int i = 0; i < start; i++)
  390. reader.Read ();
  391. int counter = 0;
  392. object [] values = new object [mapping.Length];
  393. while (reader.Read () &&
  394. (length == 0 || counter < length)) {
  395. for (int i = 0 ; i < mapping.Length; i++)
  396. values [i] = mapping [i] < 0 ? null : reader [mapping [i]];
  397. table.BeginLoadData ();
  398. table.LoadDataRow (values, loadOption);
  399. table.EndLoadData ();
  400. counter++;
  401. }
  402. return counter;
  403. }
  404. #endif // NET_2_0
  405. public override DataTable[] FillSchema (DataSet dataSet, SchemaType schemaType)
  406. {
  407. return FillSchema (dataSet, schemaType, ((IDbDataAdapter) this).SelectCommand, DefaultSourceTableName, CommandBehavior.Default);
  408. }
  409. public DataTable FillSchema (DataTable dataTable, SchemaType schemaType)
  410. {
  411. return FillSchema (dataTable, schemaType, ((IDbDataAdapter) this).SelectCommand, CommandBehavior.Default);
  412. }
  413. public DataTable[] FillSchema (DataSet dataSet, SchemaType schemaType, string srcTable)
  414. {
  415. return FillSchema (dataSet, schemaType, ((IDbDataAdapter) this).SelectCommand, srcTable, CommandBehavior.Default);
  416. }
  417. [MonoTODO ("Verify")]
  418. protected virtual DataTable FillSchema (DataTable dataTable, SchemaType schemaType, IDbCommand command, CommandBehavior behavior)
  419. {
  420. if (dataTable == null)
  421. throw new ArgumentNullException ("DataTable");
  422. behavior |= CommandBehavior.SchemaOnly | CommandBehavior.KeyInfo;
  423. if (command.Connection.State == ConnectionState.Closed) {
  424. command.Connection.Open ();
  425. behavior |= CommandBehavior.CloseConnection;
  426. }
  427. IDataReader reader = command.ExecuteReader (behavior);
  428. try
  429. {
  430. string tableName = SetupSchema (schemaType, dataTable.TableName);
  431. if (tableName != null)
  432. {
  433. BuildSchema (reader, dataTable, schemaType);
  434. }
  435. }
  436. finally
  437. {
  438. reader.Close ();
  439. }
  440. return dataTable;
  441. }
  442. [MonoTODO ("Verify")]
  443. protected virtual DataTable[] FillSchema (DataSet dataSet, SchemaType schemaType, IDbCommand command, string srcTable, CommandBehavior behavior)
  444. {
  445. if (dataSet == null)
  446. throw new ArgumentNullException ("DataSet");
  447. behavior |= CommandBehavior.SchemaOnly | CommandBehavior.KeyInfo;
  448. if (command.Connection.State == ConnectionState.Closed) {
  449. command.Connection.Open ();
  450. behavior |= CommandBehavior.CloseConnection;
  451. }
  452. IDataReader reader = command.ExecuteReader (behavior);
  453. ArrayList output = new ArrayList ();
  454. string tableName = srcTable;
  455. int index = 0;
  456. DataTable table;
  457. try
  458. {
  459. do {
  460. tableName = SetupSchema (schemaType, tableName);
  461. if (tableName != null)
  462. {
  463. if (dataSet.Tables.Contains (tableName))
  464. table = dataSet.Tables [tableName];
  465. else
  466. {
  467. table = new DataTable(tableName);
  468. dataSet.Tables.Add (table);
  469. }
  470. BuildSchema (reader, table, schemaType);
  471. output.Add (table);
  472. tableName = String.Format ("{0}{1}", srcTable, ++index);
  473. }
  474. }while (reader.NextResult ());
  475. }
  476. finally
  477. {
  478. reader.Close ();
  479. }
  480. return (DataTable[]) output.ToArray (typeof (DataTable));
  481. }
  482. #if NET_2_0
  483. [MonoTODO]
  484. public DataSet GetDataSet ()
  485. {
  486. throw new NotImplementedException ();
  487. }
  488. [MonoTODO]
  489. public DataTable GetDataTable ()
  490. {
  491. throw new NotImplementedException ();
  492. }
  493. #endif
  494. private string SetupSchema (SchemaType schemaType, string sourceTableName)
  495. {
  496. DataTableMapping tableMapping = null;
  497. if (schemaType == SchemaType.Mapped)
  498. {
  499. tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction (TableMappings, sourceTableName, sourceTableName, MissingMappingAction);
  500. if (tableMapping != null)
  501. return tableMapping.DataSetTable;
  502. return null;
  503. }
  504. else
  505. return sourceTableName;
  506. }
  507. [EditorBrowsable (EditorBrowsableState.Advanced)]
  508. public override IDataParameter[] GetFillParameters ()
  509. {
  510. IDataParameter[] parameters = new IDataParameter[SelectCommand.Parameters.Count];
  511. SelectCommand.Parameters.CopyTo (parameters, 0);
  512. return parameters;
  513. }
  514. // this method builds the schema for a given datatable. it returns a int array with
  515. // "array[ordinal of datatable column] == index of source column in data reader".
  516. // each column in the datatable has a mapping to a specific column in the datareader,
  517. // the int array represents this match.
  518. [MonoTODO ("Test")]
  519. private int[] BuildSchema (IDataReader reader, DataTable table, SchemaType schemaType)
  520. {
  521. return BuildSchema (reader, table, schemaType, MissingSchemaAction,
  522. MissingMappingAction, TableMappings);
  523. }
  524. /// <summary>
  525. /// Creates or Modifies the schema of the given DataTable based on the schema of
  526. /// the reader and the arguments passed.
  527. /// </summary>
  528. internal static int[] BuildSchema (IDataReader reader,
  529. DataTable table,
  530. SchemaType schemaType,
  531. MissingSchemaAction missingSchAction,
  532. MissingMappingAction missingMapAction,
  533. DataTableMappingCollection dtMapping
  534. )
  535. {
  536. int readerIndex = 0;
  537. // FIXME : this fails if query has fewer columns than a table
  538. int[] mapping = new int[table.Columns.Count]; // mapping the reader indexes to the datatable indexes
  539. for(int i=0; i < mapping.Length; i++) {
  540. mapping[i] = -1;
  541. }
  542. ArrayList primaryKey = new ArrayList ();
  543. ArrayList sourceColumns = new ArrayList ();
  544. bool createPrimaryKey = true;
  545. DataTable schemaTable = reader.GetSchemaTable ();
  546. DataColumn ColumnNameCol = schemaTable.Columns["ColumnName"];
  547. DataColumn DataTypeCol = schemaTable.Columns["DataType"];
  548. DataColumn IsAutoIncrementCol = schemaTable.Columns["IsAutoIncrement"];
  549. DataColumn AllowDBNullCol = schemaTable.Columns["AllowDBNull"];
  550. DataColumn IsReadOnlyCol = schemaTable.Columns["IsReadOnly"];
  551. DataColumn IsKeyCol = schemaTable.Columns["IsKey"];
  552. DataColumn IsUniqueCol = schemaTable.Columns["IsUnique"];
  553. DataColumn ColumnSizeCol = schemaTable.Columns["ColumnSize"];
  554. foreach (DataRow schemaRow in schemaTable.Rows) {
  555. // generate a unique column name in the source table.
  556. string sourceColumnName;
  557. string realSourceColumnName ;
  558. if (ColumnNameCol == null || schemaRow.IsNull(ColumnNameCol) || (string)schemaRow [ColumnNameCol] == String.Empty) {
  559. sourceColumnName = DefaultSourceColumnName;
  560. realSourceColumnName = DefaultSourceColumnName + "1";
  561. }
  562. else {
  563. sourceColumnName = (string) schemaRow [ColumnNameCol];
  564. realSourceColumnName = sourceColumnName;
  565. }
  566. for (int i = 1; sourceColumns.Contains (realSourceColumnName); i += 1)
  567. realSourceColumnName = String.Format ("{0}{1}", sourceColumnName, i);
  568. sourceColumns.Add(realSourceColumnName);
  569. // generate DataSetColumnName from DataTableMapping, if any
  570. string dsColumnName = realSourceColumnName;
  571. DataTableMapping tableMapping = null;
  572. //FIXME : The sourcetable name shud get passed as a parameter..
  573. int index = dtMapping.IndexOfDataSetTable (table.TableName);
  574. string srcTable = (index != -1 ? dtMapping[index].SourceTable : table.TableName);
  575. tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction (dtMapping, srcTable, table.TableName, missingMapAction);
  576. if (tableMapping != null)
  577. {
  578. table.TableName = tableMapping.DataSetTable;
  579. // check to see if the column mapping exists
  580. DataColumnMapping columnMapping = DataColumnMappingCollection.GetColumnMappingBySchemaAction(tableMapping.ColumnMappings, realSourceColumnName, missingMapAction);
  581. if (columnMapping != null)
  582. {
  583. Type columnType = (Type)schemaRow[DataTypeCol];
  584. DataColumn col =
  585. columnMapping.GetDataColumnBySchemaAction(
  586. table ,
  587. columnType,
  588. missingSchAction);
  589. if (col != null)
  590. {
  591. // if the column is not in the table - add it.
  592. if (table.Columns.IndexOf(col) == -1)
  593. {
  594. if (missingSchAction == MissingSchemaAction.Add
  595. || missingSchAction == MissingSchemaAction.AddWithKey)
  596. table.Columns.Add(col);
  597. int[] tmp = new int[mapping.Length + 1];
  598. Array.Copy(mapping,0,tmp,0,col.Ordinal);
  599. Array.Copy(mapping,col.Ordinal,tmp,col.Ordinal + 1,mapping.Length - col.Ordinal);
  600. mapping = tmp;
  601. }
  602. object value = (AllowDBNullCol != null) ? schemaRow[AllowDBNullCol] : null;
  603. bool allowDBNull = value is bool ? (bool)value : true;
  604. col.AllowDBNull = allowDBNull;
  605. value = (IsKeyCol != null) ? schemaRow[IsKeyCol] : null;
  606. bool isKey = value is bool ? (bool)value : false;
  607. if (missingSchAction == MissingSchemaAction.AddWithKey) {
  608. value = (IsAutoIncrementCol != null) ? schemaRow[IsAutoIncrementCol] : null;
  609. bool isAutoIncrement = value is bool ? (bool)value : false;
  610. value = (IsReadOnlyCol != null) ? schemaRow[IsReadOnlyCol] : null;
  611. bool isReadOnly = value is bool ? (bool)value : false;
  612. value = (IsUniqueCol != null) ? schemaRow[IsUniqueCol] : null;
  613. bool isUnique = value is bool ? (bool)value : false;
  614. // fill woth key info
  615. if (isAutoIncrement && DataColumn.CanAutoIncrement(columnType)) {
  616. col.AutoIncrement = true;
  617. if (!allowDBNull)
  618. col.AllowDBNull = false;
  619. }
  620. if (columnType == DbTypes.TypeOfString) {
  621. col.MaxLength = (ColumnSizeCol != null) ? (int)schemaRow[ColumnSizeCol] : 0;
  622. }
  623. if (isReadOnly)
  624. col.ReadOnly = true;
  625. if (!allowDBNull && (!isReadOnly || isKey))
  626. col.AllowDBNull = false;
  627. if (isUnique && !isKey && !columnType.IsArray) {
  628. col.Unique = true;
  629. if (!allowDBNull)
  630. col.AllowDBNull = false;
  631. }
  632. }
  633. bool isHidden = (bool) schemaRow ["IsHidden"];
  634. if (isKey && !isHidden) {
  635. primaryKey.Add (col);
  636. if (allowDBNull)
  637. createPrimaryKey = false;
  638. }
  639. // add the ordinal of the column as a key and the index of the column in the datareader as a value.
  640. mapping[col.Ordinal] = readerIndex++;
  641. }
  642. }
  643. }
  644. }
  645. if (primaryKey.Count > 0) {
  646. DataColumn[] colKey = (DataColumn[])(primaryKey.ToArray(typeof (DataColumn)));
  647. if (createPrimaryKey)
  648. table.PrimaryKey = colKey;
  649. else {
  650. UniqueConstraint uConstraint = new UniqueConstraint(colKey);
  651. for (int i = 0; i < table.Constraints.Count; i++) {
  652. if (table.Constraints[i].Equals(uConstraint)) {
  653. uConstraint = null;
  654. break;
  655. }
  656. }
  657. if (uConstraint != null)
  658. table.Constraints.Add(uConstraint);
  659. }
  660. }
  661. return mapping;
  662. }
  663. [MonoTODO]
  664. object ICloneable.Clone ()
  665. {
  666. throw new NotImplementedException ();
  667. }
  668. [MonoTODO]
  669. public int Update (DataRow[] dataRows)
  670. {
  671. if (dataRows == null)
  672. throw new ArgumentNullException("dataRows");
  673. if (dataRows.Length == 0)
  674. return 0;
  675. if (dataRows[0] == null)
  676. throw new ArgumentException("dataRows[0].");
  677. DataTable table = dataRows[0].Table;
  678. if (table == null)
  679. throw new ArgumentException("table is null reference.");
  680. // all rows must be in the same table
  681. for (int i = 0; i < dataRows.Length; i++)
  682. {
  683. if (dataRows[i] == null)
  684. throw new ArgumentException("dataRows[" + i + "].");
  685. if (dataRows[i].Table != table)
  686. throw new ArgumentException(
  687. " DataRow["
  688. + i
  689. + "] is from a different DataTable than DataRow[0].");
  690. }
  691. // get table mapping for this rows
  692. DataTableMapping tableMapping = TableMappings.GetByDataSetTable(table.TableName);
  693. if (tableMapping == null)
  694. {
  695. tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction(
  696. TableMappings,
  697. table.TableName,
  698. table.TableName,
  699. MissingMappingAction);
  700. if (tableMapping != null) {
  701. foreach (DataColumn col in table.Columns) {
  702. if (tableMapping.ColumnMappings.IndexOf (col.ColumnName) >= 0)
  703. continue;
  704. DataColumnMapping columnMapping = DataColumnMappingCollection.GetColumnMappingBySchemaAction (tableMapping.ColumnMappings, col.ColumnName, MissingMappingAction);
  705. if (columnMapping == null)
  706. columnMapping = new DataColumnMapping (col.ColumnName, col.ColumnName);
  707. tableMapping.ColumnMappings.Add (columnMapping);
  708. }
  709. } else {
  710. ArrayList cmc = new ArrayList ();
  711. foreach (DataColumn col in table.Columns)
  712. cmc.Add (new DataColumnMapping (col.ColumnName, col.ColumnName));
  713. tableMapping =
  714. new DataTableMapping (
  715. table.TableName,
  716. table.TableName,
  717. cmc.ToArray (typeof (DataColumnMapping)) as DataColumnMapping []);
  718. }
  719. }
  720. DataRow[] copy = table.NewRowArray(dataRows.Length);
  721. Array.Copy(dataRows, 0, copy, 0, dataRows.Length);
  722. return Update(copy, tableMapping);
  723. }
  724. public override int Update (DataSet dataSet)
  725. {
  726. return Update (dataSet, DefaultSourceTableName);
  727. }
  728. public int Update (DataTable dataTable)
  729. {
  730. /*
  731. int index = TableMappings.IndexOfDataSetTable (dataTable.TableName);
  732. if (index < 0)
  733. throw new ArgumentException ();
  734. return Update (dataTable, TableMappings [index]);
  735. */
  736. DataTableMapping tableMapping = TableMappings.GetByDataSetTable (dataTable.TableName);
  737. if (tableMapping == null)
  738. {
  739. tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction (
  740. TableMappings,
  741. dataTable.TableName,
  742. dataTable.TableName,
  743. MissingMappingAction);
  744. if (tableMapping != null) {
  745. foreach (DataColumn col in dataTable.Columns) {
  746. if (tableMapping.ColumnMappings.IndexOf (col.ColumnName) >= 0)
  747. continue;
  748. DataColumnMapping columnMapping = DataColumnMappingCollection.GetColumnMappingBySchemaAction (tableMapping.ColumnMappings, col.ColumnName, MissingMappingAction);
  749. if (columnMapping == null)
  750. columnMapping = new DataColumnMapping (col.ColumnName, col.ColumnName);
  751. tableMapping.ColumnMappings.Add (columnMapping);
  752. }
  753. } else {
  754. ArrayList cmc = new ArrayList ();
  755. foreach (DataColumn col in dataTable.Columns)
  756. cmc.Add (new DataColumnMapping (col.ColumnName, col.ColumnName));
  757. tableMapping =
  758. new DataTableMapping (
  759. dataTable.TableName,
  760. dataTable.TableName,
  761. cmc.ToArray (typeof (DataColumnMapping)) as DataColumnMapping []);
  762. }
  763. }
  764. return Update (dataTable, tableMapping);
  765. }
  766. private int Update (DataTable dataTable, DataTableMapping tableMapping)
  767. {
  768. DataRow[] rows = dataTable.NewRowArray(dataTable.Rows.Count);
  769. dataTable.Rows.CopyTo (rows, 0);
  770. return Update (rows, tableMapping);
  771. }
  772. [MonoTODO]
  773. protected virtual int Update (DataRow[] dataRows, DataTableMapping tableMapping)
  774. {
  775. int updateCount = 0;
  776. foreach (DataRow row in dataRows) {
  777. StatementType statementType = StatementType.Update;
  778. IDbCommand command = null;
  779. string commandName = String.Empty;
  780. switch (row.RowState) {
  781. case DataRowState.Added:
  782. statementType = StatementType.Insert;
  783. command = ((IDbDataAdapter) this).InsertCommand;
  784. commandName = "Insert";
  785. break;
  786. case DataRowState.Deleted:
  787. statementType = StatementType.Delete;
  788. command = ((IDbDataAdapter) this).DeleteCommand;
  789. commandName = "Delete";
  790. break;
  791. case DataRowState.Modified:
  792. statementType = StatementType.Update;
  793. command = ((IDbDataAdapter) this).UpdateCommand;
  794. commandName = "Update";
  795. break;
  796. case DataRowState.Unchanged:
  797. case DataRowState.Detached:
  798. continue;
  799. }
  800. RowUpdatingEventArgs argsUpdating = CreateRowUpdatingEvent (row, command, statementType, tableMapping);
  801. row.RowError = null;
  802. OnRowUpdating(argsUpdating);
  803. switch(argsUpdating.Status) {
  804. case UpdateStatus.Continue :
  805. //continue in update operation
  806. break;
  807. case UpdateStatus.ErrorsOccurred :
  808. if (argsUpdating.Errors == null) {
  809. argsUpdating.Errors = ExceptionHelper.RowUpdatedError();
  810. }
  811. row.RowError += argsUpdating.Errors.Message;
  812. if (!ContinueUpdateOnError) {
  813. throw argsUpdating.Errors;
  814. }
  815. continue;
  816. case UpdateStatus.SkipAllRemainingRows :
  817. return updateCount;
  818. case UpdateStatus.SkipCurrentRow :
  819. updateCount++;
  820. continue;
  821. default :
  822. throw ExceptionHelper.InvalidUpdateStatus(argsUpdating.Status);
  823. }
  824. command = argsUpdating.Command;
  825. try {
  826. if (command != null) {
  827. DataColumnMappingCollection columnMappings = tableMapping.ColumnMappings;
  828. foreach (IDataParameter parameter in command.Parameters) {
  829. if ((parameter.Direction & ParameterDirection.Input) != 0) {
  830. string dsColumnName = parameter.SourceColumn;
  831. if (columnMappings.Contains(parameter.SourceColumn))
  832. dsColumnName = columnMappings [parameter.SourceColumn].DataSetColumn;
  833. if (dsColumnName == null || dsColumnName.Length <= 0)
  834. continue;
  835. DataRowVersion rowVersion = parameter.SourceVersion;
  836. // Parameter version is ignored for non-update commands
  837. if (statementType == StatementType.Delete)
  838. rowVersion = DataRowVersion.Original;
  839. parameter.Value = row [dsColumnName, rowVersion];
  840. }
  841. }
  842. }
  843. }
  844. catch (Exception e) {
  845. argsUpdating.Errors = e;
  846. argsUpdating.Status = UpdateStatus.ErrorsOccurred;
  847. }
  848. IDataReader reader = null;
  849. try {
  850. if (command == null) {
  851. throw ExceptionHelper.UpdateRequiresCommand(commandName);
  852. }
  853. CommandBehavior commandBehavior = CommandBehavior.Default;
  854. if (command.Connection.State == ConnectionState.Closed) {
  855. command.Connection.Open ();
  856. commandBehavior |= CommandBehavior.CloseConnection;
  857. }
  858. // use ExecuteReader because we want to use the commandbehavior parameter.
  859. // so the connection will be closed if needed.
  860. reader = command.ExecuteReader (commandBehavior);
  861. // update the current row, if the update command returns any resultset
  862. // ignore other than the first record.
  863. DataColumnMappingCollection columnMappings = tableMapping.ColumnMappings;
  864. if (command.UpdatedRowSource == UpdateRowSource.Both ||
  865. command.UpdatedRowSource == UpdateRowSource.FirstReturnedRecord) {
  866. if (reader.Read ()){
  867. DataTable retSchema = reader.GetSchemaTable ();
  868. foreach (DataRow dr in retSchema.Rows) {
  869. string columnName = dr ["ColumnName"].ToString ();
  870. string dstColumnName = columnName;
  871. if (columnMappings != null &&
  872. columnMappings.Contains(columnName))
  873. dstColumnName = columnMappings [dstColumnName].DataSetColumn;
  874. DataColumn dstColumn = row.Table.Columns [dstColumnName];
  875. if (dstColumn == null
  876. || (dstColumn.Expression != null
  877. && dstColumn.Expression.Length > 0))
  878. continue;
  879. // info from : http://www.error-bank.com/microsoft.public.dotnet.framework.windowsforms.databinding/
  880. // [email protected]_Thread.aspx
  881. // disable readonly for non-expression columns.
  882. bool readOnlyState = dstColumn.ReadOnly;
  883. dstColumn.ReadOnly = false;
  884. try {
  885. row [dstColumnName] = reader [columnName];
  886. } finally {
  887. dstColumn.ReadOnly = readOnlyState;
  888. }
  889. }
  890. }
  891. }
  892. reader.Close ();
  893. int tmp = reader.RecordsAffected; // records affected is valid only after closing reader
  894. // if the execute does not effect any rows we throw an exception.
  895. if (tmp == 0)
  896. throw new DBConcurrencyException("Concurrency violation: the " +
  897. commandName +"Command affected 0 records.");
  898. updateCount += tmp;
  899. if (command.UpdatedRowSource == UpdateRowSource.Both ||
  900. command.UpdatedRowSource == UpdateRowSource.OutputParameters) {
  901. // Update output parameters to row values
  902. foreach (IDataParameter parameter in command.Parameters) {
  903. if (parameter.Direction != ParameterDirection.InputOutput
  904. && parameter.Direction != ParameterDirection.Output
  905. && parameter.Direction != ParameterDirection.ReturnValue)
  906. continue;
  907. string dsColumnName = parameter.SourceColumn;
  908. if (columnMappings != null &&
  909. columnMappings.Contains(parameter.SourceColumn))
  910. dsColumnName = columnMappings [parameter.SourceColumn].DataSetColumn;
  911. DataColumn dstColumn = row.Table.Columns [dsColumnName];
  912. if (dstColumn == null
  913. || (dstColumn.Expression != null
  914. && dstColumn.Expression.Length > 0))
  915. continue;
  916. bool readOnlyState = dstColumn.ReadOnly;
  917. dstColumn.ReadOnly = false;
  918. try {
  919. row [dsColumnName] = parameter.Value;
  920. } finally {
  921. dstColumn.ReadOnly = readOnlyState;
  922. }
  923. }
  924. }
  925. RowUpdatedEventArgs updatedArgs = CreateRowUpdatedEvent(row, command, statementType, tableMapping);
  926. OnRowUpdated(updatedArgs);
  927. switch(updatedArgs.Status) {
  928. case UpdateStatus.Continue:
  929. break;
  930. case UpdateStatus.ErrorsOccurred:
  931. if (updatedArgs.Errors == null) {
  932. updatedArgs.Errors = ExceptionHelper.RowUpdatedError();
  933. }
  934. row.RowError += updatedArgs.Errors.Message;
  935. if (!ContinueUpdateOnError) {
  936. throw updatedArgs.Errors;
  937. }
  938. break;
  939. case UpdateStatus.SkipCurrentRow:
  940. continue;
  941. case UpdateStatus.SkipAllRemainingRows:
  942. return updateCount;
  943. }
  944. row.AcceptChanges ();
  945. } catch(Exception e) {
  946. row.RowError = e.Message;
  947. if (!ContinueUpdateOnError) {
  948. throw e;
  949. }
  950. } finally {
  951. if (reader != null && ! reader.IsClosed) {
  952. reader.Close ();
  953. }
  954. }
  955. }
  956. return updateCount;
  957. }
  958. public int Update (DataSet dataSet, string sourceTable)
  959. {
  960. MissingMappingAction mappingAction = MissingMappingAction;
  961. if (mappingAction == MissingMappingAction.Ignore)
  962. mappingAction = MissingMappingAction.Error;
  963. DataTableMapping tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction (TableMappings, sourceTable, sourceTable, mappingAction);
  964. DataTable dataTable = dataSet.Tables[tableMapping.DataSetTable];
  965. if (dataTable == null)
  966. throw new ArgumentException (String.Format ("Missing table {0}",
  967. sourceTable));
  968. return Update (dataTable, tableMapping);
  969. }
  970. #if ONLY_1_0 || ONLY_1_1
  971. protected virtual void OnFillError (FillErrorEventArgs value)
  972. {
  973. if (FillError != null)
  974. FillError (this, value);
  975. }
  976. #endif
  977. protected abstract void OnRowUpdated (RowUpdatedEventArgs value);
  978. protected abstract void OnRowUpdating (RowUpdatingEventArgs value);
  979. #endregion // Methods
  980. }
  981. }