DbDataAdapter.cs 34 KB

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