DbDataAdapter.cs 37 KB

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