DbDataAdapter.cs 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156
  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. // FillSchema should add the KeyInfo unless MissingSchemaAction
  434. // is set to Ignore or Error.
  435. MissingSchemaAction schemaAction = MissingSchemaAction;
  436. if (!(schemaAction == MissingSchemaAction.Ignore ||
  437. schemaAction == MissingSchemaAction.Error))
  438. schemaAction = MissingSchemaAction.AddWithKey;
  439. BuildSchema (reader, dataTable, schemaType, schemaAction,
  440. MissingMappingAction, TableMappings);
  441. }
  442. }
  443. finally
  444. {
  445. reader.Close ();
  446. }
  447. return dataTable;
  448. }
  449. [MonoTODO ("Verify")]
  450. protected virtual DataTable[] FillSchema (DataSet dataSet, SchemaType schemaType, IDbCommand command, string srcTable, CommandBehavior behavior)
  451. {
  452. if (dataSet == null)
  453. throw new ArgumentNullException ("DataSet");
  454. behavior |= CommandBehavior.SchemaOnly | CommandBehavior.KeyInfo;
  455. if (command.Connection.State == ConnectionState.Closed) {
  456. command.Connection.Open ();
  457. behavior |= CommandBehavior.CloseConnection;
  458. }
  459. IDataReader reader = command.ExecuteReader (behavior);
  460. ArrayList output = new ArrayList ();
  461. string tableName = srcTable;
  462. int index = 0;
  463. DataTable table;
  464. try
  465. {
  466. // FillSchema should add the KeyInfo unless MissingSchemaAction
  467. // is set to Ignore or Error.
  468. MissingSchemaAction schemaAction = MissingSchemaAction;
  469. if (!(MissingSchemaAction == MissingSchemaAction.Ignore ||
  470. MissingSchemaAction == MissingSchemaAction.Error))
  471. schemaAction = MissingSchemaAction.AddWithKey;
  472. do {
  473. tableName = SetupSchema (schemaType, tableName);
  474. if (tableName != null)
  475. {
  476. if (dataSet.Tables.Contains (tableName))
  477. table = dataSet.Tables [tableName];
  478. else
  479. {
  480. // Do not create schema if MissingSchemAction is set to Ignore
  481. if (this.MissingSchemaAction == MissingSchemaAction.Ignore)
  482. continue;
  483. table = dataSet.Tables.Add (tableName);
  484. }
  485. BuildSchema (reader, table, schemaType, schemaAction,
  486. MissingMappingAction, TableMappings);
  487. output.Add (table);
  488. tableName = String.Format ("{0}{1}", srcTable, ++index);
  489. }
  490. }while (reader.NextResult ());
  491. }
  492. finally
  493. {
  494. reader.Close ();
  495. }
  496. return (DataTable[]) output.ToArray (typeof (DataTable));
  497. }
  498. #if NET_2_0
  499. [MonoTODO]
  500. public DataSet GetDataSet ()
  501. {
  502. throw new NotImplementedException ();
  503. }
  504. [MonoTODO]
  505. public DataTable GetDataTable ()
  506. {
  507. throw new NotImplementedException ();
  508. }
  509. #endif
  510. private string SetupSchema (SchemaType schemaType, string sourceTableName)
  511. {
  512. DataTableMapping tableMapping = null;
  513. if (schemaType == SchemaType.Mapped)
  514. {
  515. tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction (TableMappings, sourceTableName, sourceTableName, MissingMappingAction);
  516. if (tableMapping != null)
  517. return tableMapping.DataSetTable;
  518. return null;
  519. }
  520. else
  521. return sourceTableName;
  522. }
  523. [EditorBrowsable (EditorBrowsableState.Advanced)]
  524. public override IDataParameter[] GetFillParameters ()
  525. {
  526. IDataParameter[] parameters = new IDataParameter[SelectCommand.Parameters.Count];
  527. SelectCommand.Parameters.CopyTo (parameters, 0);
  528. return parameters;
  529. }
  530. // this method builds the schema for a given datatable. it returns a int array with
  531. // "array[ordinal of datatable column] == index of source column in data reader".
  532. // each column in the datatable has a mapping to a specific column in the datareader,
  533. // the int array represents this match.
  534. [MonoTODO ("Test")]
  535. private int[] BuildSchema (IDataReader reader, DataTable table, SchemaType schemaType)
  536. {
  537. return BuildSchema (reader, table, schemaType, MissingSchemaAction,
  538. MissingMappingAction, TableMappings);
  539. }
  540. /// <summary>
  541. /// Creates or Modifies the schema of the given DataTable based on the schema of
  542. /// the reader and the arguments passed.
  543. /// </summary>
  544. internal static int[] BuildSchema (IDataReader reader,
  545. DataTable table,
  546. SchemaType schemaType,
  547. MissingSchemaAction missingSchAction,
  548. MissingMappingAction missingMapAction,
  549. DataTableMappingCollection dtMapping
  550. )
  551. {
  552. int readerIndex = 0;
  553. // FIXME : this fails if query has fewer columns than a table
  554. int[] mapping = new int[table.Columns.Count]; // mapping the reader indexes to the datatable indexes
  555. for(int i=0; i < mapping.Length; i++) {
  556. mapping[i] = -1;
  557. }
  558. ArrayList primaryKey = new ArrayList ();
  559. ArrayList sourceColumns = new ArrayList ();
  560. bool createPrimaryKey = true;
  561. DataTable schemaTable = reader.GetSchemaTable ();
  562. DataColumn ColumnNameCol = schemaTable.Columns["ColumnName"];
  563. DataColumn DataTypeCol = schemaTable.Columns["DataType"];
  564. DataColumn IsAutoIncrementCol = schemaTable.Columns["IsAutoIncrement"];
  565. DataColumn AllowDBNullCol = schemaTable.Columns["AllowDBNull"];
  566. DataColumn IsReadOnlyCol = schemaTable.Columns["IsReadOnly"];
  567. DataColumn IsKeyCol = schemaTable.Columns["IsKey"];
  568. DataColumn IsUniqueCol = schemaTable.Columns["IsUnique"];
  569. DataColumn ColumnSizeCol = schemaTable.Columns["ColumnSize"];
  570. foreach (DataRow schemaRow in schemaTable.Rows) {
  571. // generate a unique column name in the source table.
  572. string sourceColumnName;
  573. string realSourceColumnName ;
  574. if (ColumnNameCol == null || schemaRow.IsNull(ColumnNameCol) || (string)schemaRow [ColumnNameCol] == String.Empty) {
  575. sourceColumnName = DefaultSourceColumnName;
  576. realSourceColumnName = DefaultSourceColumnName + "1";
  577. }
  578. else {
  579. sourceColumnName = (string) schemaRow [ColumnNameCol];
  580. realSourceColumnName = sourceColumnName;
  581. }
  582. for (int i = 1; sourceColumns.Contains (realSourceColumnName); i += 1)
  583. realSourceColumnName = String.Format ("{0}{1}", sourceColumnName, i);
  584. sourceColumns.Add(realSourceColumnName);
  585. // generate DataSetColumnName from DataTableMapping, if any
  586. string dsColumnName = realSourceColumnName;
  587. DataTableMapping tableMapping = null;
  588. //FIXME : The sourcetable name shud get passed as a parameter..
  589. int index = dtMapping.IndexOfDataSetTable (table.TableName);
  590. string srcTable = (index != -1 ? dtMapping[index].SourceTable : table.TableName);
  591. tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction (dtMapping, srcTable, table.TableName, missingMapAction);
  592. if (tableMapping != null)
  593. {
  594. table.TableName = tableMapping.DataSetTable;
  595. // check to see if the column mapping exists
  596. DataColumnMapping columnMapping = DataColumnMappingCollection.GetColumnMappingBySchemaAction(tableMapping.ColumnMappings, realSourceColumnName, missingMapAction);
  597. if (columnMapping != null)
  598. {
  599. Type columnType = (Type)schemaRow[DataTypeCol];
  600. DataColumn col =
  601. columnMapping.GetDataColumnBySchemaAction(
  602. table ,
  603. columnType,
  604. missingSchAction);
  605. if (col != null)
  606. {
  607. // if the column is not in the table - add it.
  608. if (table.Columns.IndexOf(col) == -1)
  609. {
  610. if (missingSchAction == MissingSchemaAction.Add
  611. || missingSchAction == MissingSchemaAction.AddWithKey)
  612. table.Columns.Add(col);
  613. int[] tmp = new int[mapping.Length + 1];
  614. Array.Copy(mapping,0,tmp,0,col.Ordinal);
  615. Array.Copy(mapping,col.Ordinal,tmp,col.Ordinal + 1,mapping.Length - col.Ordinal);
  616. mapping = tmp;
  617. }
  618. if (missingSchAction == MissingSchemaAction.AddWithKey) {
  619. object value = (AllowDBNullCol != null) ? schemaRow[AllowDBNullCol] : null;
  620. bool allowDBNull = value is bool ? (bool)value : true;
  621. value = (IsKeyCol != null) ? schemaRow[IsKeyCol] : null;
  622. bool isKey = value is bool ? (bool)value : false;
  623. value = (IsAutoIncrementCol != null) ? schemaRow[IsAutoIncrementCol] : null;
  624. bool isAutoIncrement = value is bool ? (bool)value : false;
  625. value = (IsReadOnlyCol != null) ? schemaRow[IsReadOnlyCol] : null;
  626. bool isReadOnly = value is bool ? (bool)value : false;
  627. value = (IsUniqueCol != null) ? schemaRow[IsUniqueCol] : null;
  628. bool isUnique = value is bool ? (bool)value : false;
  629. col.AllowDBNull = allowDBNull;
  630. // fill woth key info
  631. if (isAutoIncrement && DataColumn.CanAutoIncrement(columnType)) {
  632. col.AutoIncrement = true;
  633. if (!allowDBNull)
  634. col.AllowDBNull = false;
  635. }
  636. if (columnType == DbTypes.TypeOfString) {
  637. col.MaxLength = (ColumnSizeCol != null) ? (int)schemaRow[ColumnSizeCol] : 0;
  638. }
  639. if (isReadOnly)
  640. col.ReadOnly = true;
  641. if (!allowDBNull && (!isReadOnly || isKey))
  642. col.AllowDBNull = false;
  643. if (isUnique && !isKey && !columnType.IsArray) {
  644. col.Unique = true;
  645. if (!allowDBNull)
  646. col.AllowDBNull = false;
  647. }
  648. // This might not be set by all DataProviders
  649. bool isHidden = false;
  650. if (schemaTable.Columns.Contains ("IsHidden")) {
  651. value = schemaRow["IsHidden"];
  652. isHidden = ((value is bool) ? (bool)value : false);
  653. }
  654. if (isKey && !isHidden) {
  655. primaryKey.Add (col);
  656. if (allowDBNull)
  657. createPrimaryKey = false;
  658. }
  659. }
  660. // add the ordinal of the column as a key and the index of the column in the datareader as a value.
  661. mapping[col.Ordinal] = readerIndex++;
  662. }
  663. }
  664. }
  665. }
  666. if (primaryKey.Count > 0) {
  667. DataColumn[] colKey = (DataColumn[])(primaryKey.ToArray(typeof (DataColumn)));
  668. if (createPrimaryKey)
  669. table.PrimaryKey = colKey;
  670. else {
  671. UniqueConstraint uConstraint = new UniqueConstraint(colKey);
  672. for (int i = 0; i < table.Constraints.Count; i++) {
  673. if (table.Constraints[i].Equals(uConstraint)) {
  674. uConstraint = null;
  675. break;
  676. }
  677. }
  678. if (uConstraint != null)
  679. table.Constraints.Add(uConstraint);
  680. }
  681. }
  682. return mapping;
  683. }
  684. [MonoTODO]
  685. object ICloneable.Clone ()
  686. {
  687. throw new NotImplementedException ();
  688. }
  689. [MonoTODO]
  690. public int Update (DataRow[] dataRows)
  691. {
  692. if (dataRows == null)
  693. throw new ArgumentNullException("dataRows");
  694. if (dataRows.Length == 0)
  695. return 0;
  696. if (dataRows[0] == null)
  697. throw new ArgumentException("dataRows[0].");
  698. DataTable table = dataRows[0].Table;
  699. if (table == null)
  700. throw new ArgumentException("table is null reference.");
  701. // all rows must be in the same table
  702. for (int i = 0; i < dataRows.Length; i++)
  703. {
  704. if (dataRows[i] == null)
  705. throw new ArgumentException("dataRows[" + i + "].");
  706. if (dataRows[i].Table != table)
  707. throw new ArgumentException(
  708. " DataRow["
  709. + i
  710. + "] is from a different DataTable than DataRow[0].");
  711. }
  712. // get table mapping for this rows
  713. DataTableMapping tableMapping = TableMappings.GetByDataSetTable(table.TableName);
  714. if (tableMapping == null)
  715. {
  716. tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction(
  717. TableMappings,
  718. table.TableName,
  719. table.TableName,
  720. MissingMappingAction);
  721. if (tableMapping != null) {
  722. foreach (DataColumn col in table.Columns) {
  723. if (tableMapping.ColumnMappings.IndexOf (col.ColumnName) >= 0)
  724. continue;
  725. DataColumnMapping columnMapping = DataColumnMappingCollection.GetColumnMappingBySchemaAction (tableMapping.ColumnMappings, col.ColumnName, MissingMappingAction);
  726. if (columnMapping == null)
  727. columnMapping = new DataColumnMapping (col.ColumnName, col.ColumnName);
  728. tableMapping.ColumnMappings.Add (columnMapping);
  729. }
  730. } else {
  731. ArrayList cmc = new ArrayList ();
  732. foreach (DataColumn col in table.Columns)
  733. cmc.Add (new DataColumnMapping (col.ColumnName, col.ColumnName));
  734. tableMapping =
  735. new DataTableMapping (
  736. table.TableName,
  737. table.TableName,
  738. cmc.ToArray (typeof (DataColumnMapping)) as DataColumnMapping []);
  739. }
  740. }
  741. DataRow[] copy = table.NewRowArray(dataRows.Length);
  742. Array.Copy(dataRows, 0, copy, 0, dataRows.Length);
  743. return Update(copy, tableMapping);
  744. }
  745. public override int Update (DataSet dataSet)
  746. {
  747. return Update (dataSet, DefaultSourceTableName);
  748. }
  749. public int Update (DataTable dataTable)
  750. {
  751. /*
  752. int index = TableMappings.IndexOfDataSetTable (dataTable.TableName);
  753. if (index < 0)
  754. throw new ArgumentException ();
  755. return Update (dataTable, TableMappings [index]);
  756. */
  757. DataTableMapping tableMapping = TableMappings.GetByDataSetTable (dataTable.TableName);
  758. if (tableMapping == null)
  759. {
  760. tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction (
  761. TableMappings,
  762. dataTable.TableName,
  763. dataTable.TableName,
  764. MissingMappingAction);
  765. if (tableMapping != null) {
  766. foreach (DataColumn col in dataTable.Columns) {
  767. if (tableMapping.ColumnMappings.IndexOf (col.ColumnName) >= 0)
  768. continue;
  769. DataColumnMapping columnMapping = DataColumnMappingCollection.GetColumnMappingBySchemaAction (tableMapping.ColumnMappings, col.ColumnName, MissingMappingAction);
  770. if (columnMapping == null)
  771. columnMapping = new DataColumnMapping (col.ColumnName, col.ColumnName);
  772. tableMapping.ColumnMappings.Add (columnMapping);
  773. }
  774. } else {
  775. ArrayList cmc = new ArrayList ();
  776. foreach (DataColumn col in dataTable.Columns)
  777. cmc.Add (new DataColumnMapping (col.ColumnName, col.ColumnName));
  778. tableMapping =
  779. new DataTableMapping (
  780. dataTable.TableName,
  781. dataTable.TableName,
  782. cmc.ToArray (typeof (DataColumnMapping)) as DataColumnMapping []);
  783. }
  784. }
  785. return Update (dataTable, tableMapping);
  786. }
  787. private int Update (DataTable dataTable, DataTableMapping tableMapping)
  788. {
  789. DataRow[] rows = dataTable.NewRowArray(dataTable.Rows.Count);
  790. dataTable.Rows.CopyTo (rows, 0);
  791. return Update (rows, tableMapping);
  792. }
  793. [MonoTODO]
  794. protected virtual int Update (DataRow[] dataRows, DataTableMapping tableMapping)
  795. {
  796. int updateCount = 0;
  797. foreach (DataRow row in dataRows) {
  798. StatementType statementType = StatementType.Update;
  799. IDbCommand command = null;
  800. string commandName = String.Empty;
  801. switch (row.RowState) {
  802. case DataRowState.Added:
  803. statementType = StatementType.Insert;
  804. command = ((IDbDataAdapter) this).InsertCommand;
  805. commandName = "Insert";
  806. break;
  807. case DataRowState.Deleted:
  808. statementType = StatementType.Delete;
  809. command = ((IDbDataAdapter) this).DeleteCommand;
  810. commandName = "Delete";
  811. break;
  812. case DataRowState.Modified:
  813. statementType = StatementType.Update;
  814. command = ((IDbDataAdapter) this).UpdateCommand;
  815. commandName = "Update";
  816. break;
  817. case DataRowState.Unchanged:
  818. case DataRowState.Detached:
  819. continue;
  820. }
  821. RowUpdatingEventArgs argsUpdating = CreateRowUpdatingEvent (row, command, statementType, tableMapping);
  822. row.RowError = null;
  823. OnRowUpdating(argsUpdating);
  824. switch(argsUpdating.Status) {
  825. case UpdateStatus.Continue :
  826. //continue in update operation
  827. break;
  828. case UpdateStatus.ErrorsOccurred :
  829. if (argsUpdating.Errors == null) {
  830. argsUpdating.Errors = ExceptionHelper.RowUpdatedError();
  831. }
  832. row.RowError += argsUpdating.Errors.Message;
  833. if (!ContinueUpdateOnError) {
  834. throw argsUpdating.Errors;
  835. }
  836. continue;
  837. case UpdateStatus.SkipAllRemainingRows :
  838. return updateCount;
  839. case UpdateStatus.SkipCurrentRow :
  840. updateCount++;
  841. continue;
  842. default :
  843. throw ExceptionHelper.InvalidUpdateStatus(argsUpdating.Status);
  844. }
  845. command = argsUpdating.Command;
  846. try {
  847. if (command != null) {
  848. DataColumnMappingCollection columnMappings = tableMapping.ColumnMappings;
  849. foreach (IDataParameter parameter in command.Parameters) {
  850. if ((parameter.Direction & ParameterDirection.Input) != 0) {
  851. string dsColumnName = parameter.SourceColumn;
  852. if (columnMappings.Contains(parameter.SourceColumn))
  853. dsColumnName = columnMappings [parameter.SourceColumn].DataSetColumn;
  854. if (dsColumnName == null || dsColumnName.Length <= 0)
  855. continue;
  856. DataRowVersion rowVersion = parameter.SourceVersion;
  857. // Parameter version is ignored for non-update commands
  858. if (statementType == StatementType.Delete)
  859. rowVersion = DataRowVersion.Original;
  860. parameter.Value = row [dsColumnName, rowVersion];
  861. }
  862. }
  863. }
  864. }
  865. catch (Exception e) {
  866. argsUpdating.Errors = e;
  867. argsUpdating.Status = UpdateStatus.ErrorsOccurred;
  868. }
  869. IDataReader reader = null;
  870. try {
  871. if (command == null) {
  872. throw ExceptionHelper.UpdateRequiresCommand(commandName);
  873. }
  874. CommandBehavior commandBehavior = CommandBehavior.Default;
  875. if (command.Connection.State == ConnectionState.Closed) {
  876. command.Connection.Open ();
  877. commandBehavior |= CommandBehavior.CloseConnection;
  878. }
  879. // use ExecuteReader because we want to use the commandbehavior parameter.
  880. // so the connection will be closed if needed.
  881. reader = command.ExecuteReader (commandBehavior);
  882. // update the current row, if the update command returns any resultset
  883. // ignore other than the first record.
  884. DataColumnMappingCollection columnMappings = tableMapping.ColumnMappings;
  885. if (command.UpdatedRowSource == UpdateRowSource.Both ||
  886. command.UpdatedRowSource == UpdateRowSource.FirstReturnedRecord) {
  887. if (reader.Read ()){
  888. DataTable retSchema = reader.GetSchemaTable ();
  889. foreach (DataRow dr in retSchema.Rows) {
  890. string columnName = dr ["ColumnName"].ToString ();
  891. string dstColumnName = columnName;
  892. if (columnMappings != null &&
  893. columnMappings.Contains(columnName))
  894. dstColumnName = columnMappings [dstColumnName].DataSetColumn;
  895. DataColumn dstColumn = row.Table.Columns [dstColumnName];
  896. if (dstColumn == null
  897. || (dstColumn.Expression != null
  898. && dstColumn.Expression.Length > 0))
  899. continue;
  900. // info from : http://www.error-bank.com/microsoft.public.dotnet.framework.windowsforms.databinding/
  901. // [email protected]_Thread.aspx
  902. // disable readonly for non-expression columns.
  903. bool readOnlyState = dstColumn.ReadOnly;
  904. dstColumn.ReadOnly = false;
  905. try {
  906. row [dstColumnName] = reader [columnName];
  907. } finally {
  908. dstColumn.ReadOnly = readOnlyState;
  909. }
  910. }
  911. }
  912. }
  913. reader.Close ();
  914. int tmp = reader.RecordsAffected; // records affected is valid only after closing reader
  915. // if the execute does not effect any rows we throw an exception.
  916. if (tmp == 0)
  917. throw new DBConcurrencyException("Concurrency violation: the " +
  918. commandName +"Command affected 0 records.");
  919. updateCount += tmp;
  920. if (command.UpdatedRowSource == UpdateRowSource.Both ||
  921. command.UpdatedRowSource == UpdateRowSource.OutputParameters) {
  922. // Update output parameters to row values
  923. foreach (IDataParameter parameter in command.Parameters) {
  924. if (parameter.Direction != ParameterDirection.InputOutput
  925. && parameter.Direction != ParameterDirection.Output
  926. && parameter.Direction != ParameterDirection.ReturnValue)
  927. continue;
  928. string dsColumnName = parameter.SourceColumn;
  929. if (columnMappings != null &&
  930. columnMappings.Contains(parameter.SourceColumn))
  931. dsColumnName = columnMappings [parameter.SourceColumn].DataSetColumn;
  932. DataColumn dstColumn = row.Table.Columns [dsColumnName];
  933. if (dstColumn == null
  934. || (dstColumn.Expression != null
  935. && dstColumn.Expression.Length > 0))
  936. continue;
  937. bool readOnlyState = dstColumn.ReadOnly;
  938. dstColumn.ReadOnly = false;
  939. try {
  940. row [dsColumnName] = parameter.Value;
  941. } finally {
  942. dstColumn.ReadOnly = readOnlyState;
  943. }
  944. }
  945. }
  946. RowUpdatedEventArgs updatedArgs = CreateRowUpdatedEvent(row, command, statementType, tableMapping);
  947. OnRowUpdated(updatedArgs);
  948. switch(updatedArgs.Status) {
  949. case UpdateStatus.Continue:
  950. break;
  951. case UpdateStatus.ErrorsOccurred:
  952. if (updatedArgs.Errors == null) {
  953. updatedArgs.Errors = ExceptionHelper.RowUpdatedError();
  954. }
  955. row.RowError += updatedArgs.Errors.Message;
  956. if (!ContinueUpdateOnError) {
  957. throw updatedArgs.Errors;
  958. }
  959. break;
  960. case UpdateStatus.SkipCurrentRow:
  961. continue;
  962. case UpdateStatus.SkipAllRemainingRows:
  963. return updateCount;
  964. }
  965. row.AcceptChanges ();
  966. } catch(Exception e) {
  967. row.RowError = e.Message;
  968. if (!ContinueUpdateOnError) {
  969. throw e;
  970. }
  971. } finally {
  972. if (reader != null && ! reader.IsClosed) {
  973. reader.Close ();
  974. }
  975. }
  976. }
  977. return updateCount;
  978. }
  979. public int Update (DataSet dataSet, string sourceTable)
  980. {
  981. MissingMappingAction mappingAction = MissingMappingAction;
  982. if (mappingAction == MissingMappingAction.Ignore)
  983. mappingAction = MissingMappingAction.Error;
  984. DataTableMapping tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction (TableMappings, sourceTable, sourceTable, mappingAction);
  985. DataTable dataTable = dataSet.Tables[tableMapping.DataSetTable];
  986. if (dataTable == null)
  987. throw new ArgumentException (String.Format ("Missing table {0}",
  988. sourceTable));
  989. return Update (dataTable, tableMapping);
  990. }
  991. #if ONLY_1_0 || ONLY_1_1
  992. protected virtual void OnFillError (FillErrorEventArgs value)
  993. {
  994. if (FillError != null)
  995. FillError (this, value);
  996. }
  997. #endif
  998. protected abstract void OnRowUpdated (RowUpdatedEventArgs value);
  999. protected abstract void OnRowUpdating (RowUpdatingEventArgs value);
  1000. #endregion // Methods
  1001. }
  1002. }