DbDataAdapter.cs 36 KB

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