DbDataAdapter.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  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. col.AllowDBNull = allowDBNull;
  545. value = (IsKeyCol != null) ? schemaRow[IsKeyCol] : null;
  546. bool isKey = value is bool ? (bool)value : false;
  547. if (missingSchAction == MissingSchemaAction.AddWithKey) {
  548. value = (IsAutoIncrementCol != null) ? schemaRow[IsAutoIncrementCol] : null;
  549. bool isAutoIncrement = value is bool ? (bool)value : false;
  550. value = (IsReadOnlyCol != null) ? schemaRow[IsReadOnlyCol] : null;
  551. bool isReadOnly = value is bool ? (bool)value : false;
  552. value = (IsUniqueCol != null) ? schemaRow[IsUniqueCol] : null;
  553. bool isUnique = value is bool ? (bool)value : false;
  554. // fill woth key info
  555. if (isAutoIncrement && DataColumn.CanAutoIncrement(columnType)) {
  556. col.AutoIncrement = true;
  557. if (!allowDBNull)
  558. col.AllowDBNull = false;
  559. }
  560. if (columnType == DbTypes.TypeOfString) {
  561. col.MaxLength = (ColumnSizeCol != null) ? (int)schemaRow[ColumnSizeCol] : 0;
  562. }
  563. if (isReadOnly)
  564. col.ReadOnly = true;
  565. if (!allowDBNull && (!isReadOnly || isKey))
  566. col.AllowDBNull = false;
  567. if (isUnique && !isKey && !columnType.IsArray) {
  568. col.Unique = true;
  569. if (!allowDBNull)
  570. col.AllowDBNull = false;
  571. }
  572. }
  573. if (isKey) {
  574. primaryKey.Add (col);
  575. if (allowDBNull)
  576. createPrimaryKey = false;
  577. }
  578. // add the ordinal of the column as a key and the index of the column in the datareader as a value.
  579. mapping[col.Ordinal] = readerIndex++;
  580. }
  581. }
  582. }
  583. }
  584. if (primaryKey.Count > 0) {
  585. DataColumn[] colKey = (DataColumn[])(primaryKey.ToArray(typeof (DataColumn)));
  586. if (createPrimaryKey)
  587. table.PrimaryKey = colKey;
  588. else {
  589. UniqueConstraint uConstraint = new UniqueConstraint(colKey);
  590. for (int i = 0; i < table.Constraints.Count; i++) {
  591. if (table.Constraints[i].Equals(uConstraint)) {
  592. uConstraint = null;
  593. break;
  594. }
  595. }
  596. if (uConstraint != null)
  597. table.Constraints.Add(uConstraint);
  598. }
  599. }
  600. return mapping;
  601. }
  602. [MonoTODO]
  603. object ICloneable.Clone ()
  604. {
  605. throw new NotImplementedException ();
  606. }
  607. [MonoTODO]
  608. public int Update (DataRow[] dataRows)
  609. {
  610. if (dataRows == null)
  611. throw new ArgumentNullException("dataRows");
  612. if (dataRows.Length == 0)
  613. return 0;
  614. if (dataRows[0] == null)
  615. throw new ArgumentException("dataRows[0].");
  616. DataTable table = dataRows[0].Table;
  617. if (table == null)
  618. throw new ArgumentException("table is null reference.");
  619. // all rows must be in the same table
  620. for (int i = 0; i < dataRows.Length; i++)
  621. {
  622. if (dataRows[i] == null)
  623. throw new ArgumentException("dataRows[" + i + "].");
  624. if (dataRows[i].Table != table)
  625. throw new ArgumentException(
  626. " DataRow["
  627. + i
  628. + "] is from a different DataTable than DataRow[0].");
  629. }
  630. // get table mapping for this rows
  631. DataTableMapping tableMapping = TableMappings.GetByDataSetTable(table.TableName);
  632. if (tableMapping == null)
  633. {
  634. tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction(
  635. TableMappings,
  636. table.TableName,
  637. table.TableName,
  638. MissingMappingAction);
  639. if (tableMapping != null) {
  640. foreach (DataColumn col in table.Columns) {
  641. if (tableMapping.ColumnMappings.IndexOf (col.ColumnName) >= 0)
  642. continue;
  643. DataColumnMapping columnMapping = DataColumnMappingCollection.GetColumnMappingBySchemaAction (tableMapping.ColumnMappings, col.ColumnName, MissingMappingAction);
  644. if (columnMapping == null)
  645. columnMapping = new DataColumnMapping (col.ColumnName, col.ColumnName);
  646. tableMapping.ColumnMappings.Add (columnMapping);
  647. }
  648. } else {
  649. ArrayList cmc = new ArrayList ();
  650. foreach (DataColumn col in table.Columns)
  651. cmc.Add (new DataColumnMapping (col.ColumnName, col.ColumnName));
  652. tableMapping =
  653. new DataTableMapping (
  654. table.TableName,
  655. table.TableName,
  656. cmc.ToArray (typeof (DataColumnMapping)) as DataColumnMapping []);
  657. }
  658. }
  659. DataRow[] copy = table.NewRowArray(dataRows.Length);
  660. Array.Copy(dataRows, 0, copy, 0, dataRows.Length);
  661. return Update(copy, tableMapping);
  662. }
  663. public override int Update (DataSet dataSet)
  664. {
  665. return Update (dataSet, DefaultSourceTableName);
  666. }
  667. public int Update (DataTable dataTable)
  668. {
  669. /*
  670. int index = TableMappings.IndexOfDataSetTable (dataTable.TableName);
  671. if (index < 0)
  672. throw new ArgumentException ();
  673. return Update (dataTable, TableMappings [index]);
  674. */
  675. DataTableMapping tableMapping = TableMappings.GetByDataSetTable (dataTable.TableName);
  676. if (tableMapping == null)
  677. {
  678. tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction (
  679. TableMappings,
  680. dataTable.TableName,
  681. dataTable.TableName,
  682. MissingMappingAction);
  683. if (tableMapping != null) {
  684. foreach (DataColumn col in dataTable.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 dataTable.Columns)
  695. cmc.Add (new DataColumnMapping (col.ColumnName, col.ColumnName));
  696. tableMapping =
  697. new DataTableMapping (
  698. dataTable.TableName,
  699. dataTable.TableName,
  700. cmc.ToArray (typeof (DataColumnMapping)) as DataColumnMapping []);
  701. }
  702. }
  703. return Update (dataTable, tableMapping);
  704. }
  705. private int Update (DataTable dataTable, DataTableMapping tableMapping)
  706. {
  707. DataRow[] rows = dataTable.NewRowArray(dataTable.Rows.Count);
  708. dataTable.Rows.CopyTo (rows, 0);
  709. return Update (rows, tableMapping);
  710. }
  711. [MonoTODO]
  712. protected virtual int Update (DataRow[] dataRows, DataTableMapping tableMapping)
  713. {
  714. int updateCount = 0;
  715. foreach (DataRow row in dataRows) {
  716. StatementType statementType = StatementType.Update;
  717. IDbCommand command = null;
  718. string commandName = String.Empty;
  719. switch (row.RowState) {
  720. case DataRowState.Added:
  721. statementType = StatementType.Insert;
  722. command = InsertCommand;
  723. commandName = "Insert";
  724. break;
  725. case DataRowState.Deleted:
  726. statementType = StatementType.Delete;
  727. command = DeleteCommand;
  728. commandName = "Delete";
  729. break;
  730. case DataRowState.Modified:
  731. statementType = StatementType.Update;
  732. command = UpdateCommand;
  733. commandName = "Update";
  734. break;
  735. case DataRowState.Unchanged:
  736. case DataRowState.Detached:
  737. continue;
  738. }
  739. RowUpdatingEventArgs argsUpdating = CreateRowUpdatingEvent (row, command, statementType, tableMapping);
  740. row.RowError = null;
  741. OnRowUpdating(argsUpdating);
  742. switch(argsUpdating.Status) {
  743. case UpdateStatus.Continue :
  744. //continue in update operation
  745. break;
  746. case UpdateStatus.ErrorsOccurred :
  747. if (argsUpdating.Errors == null) {
  748. argsUpdating.Errors = ExceptionHelper.RowUpdatedError();
  749. }
  750. row.RowError += argsUpdating.Errors.Message;
  751. if (!ContinueUpdateOnError) {
  752. throw argsUpdating.Errors;
  753. }
  754. continue;
  755. case UpdateStatus.SkipAllRemainingRows :
  756. return updateCount;
  757. case UpdateStatus.SkipCurrentRow :
  758. updateCount++;
  759. continue;
  760. default :
  761. throw ExceptionHelper.InvalidUpdateStatus(argsUpdating.Status);
  762. }
  763. command = argsUpdating.Command;
  764. try {
  765. if (command != null) {
  766. DataColumnMappingCollection columnMappings = tableMapping.ColumnMappings;
  767. foreach (IDataParameter parameter in command.Parameters) {
  768. if ((parameter.Direction & ParameterDirection.Input) != 0) {
  769. string dsColumnName = parameter.SourceColumn;
  770. if (columnMappings.Contains(parameter.SourceColumn))
  771. dsColumnName = columnMappings [parameter.SourceColumn].DataSetColumn;
  772. if (dsColumnName == null || dsColumnName.Length <= 0)
  773. continue;
  774. DataRowVersion rowVersion = parameter.SourceVersion;
  775. // Parameter version is ignored for non-update commands
  776. if (statementType == StatementType.Delete)
  777. rowVersion = DataRowVersion.Original;
  778. parameter.Value = row [dsColumnName, rowVersion];
  779. }
  780. }
  781. }
  782. }
  783. catch (Exception e) {
  784. argsUpdating.Errors = e;
  785. argsUpdating.Status = UpdateStatus.ErrorsOccurred;
  786. }
  787. IDataReader reader = null;
  788. try {
  789. if (command == null) {
  790. throw ExceptionHelper.UpdateRequiresCommand(commandName);
  791. }
  792. CommandBehavior commandBehavior = CommandBehavior.Default;
  793. if (command.Connection.State == ConnectionState.Closed) {
  794. command.Connection.Open ();
  795. commandBehavior |= CommandBehavior.CloseConnection;
  796. }
  797. // use ExecuteReader because we want to use the commandbehavior parameter.
  798. // so the connection will be closed if needed.
  799. reader = command.ExecuteReader (commandBehavior);
  800. // update the current row, if the update command returns any resultset
  801. // ignore other than the first record.
  802. DataColumnMappingCollection columnMappings = tableMapping.ColumnMappings;
  803. if (command.UpdatedRowSource == UpdateRowSource.Both ||
  804. command.UpdatedRowSource == UpdateRowSource.FirstReturnedRecord) {
  805. if (reader.Read ()){
  806. DataTable retSchema = reader.GetSchemaTable ();
  807. foreach (DataRow dr in retSchema.Rows) {
  808. string columnName = dr ["ColumnName"].ToString ();
  809. string dstColumnName = columnName;
  810. if (columnMappings != null &&
  811. columnMappings.Contains(columnName))
  812. dstColumnName = columnMappings [dstColumnName].DataSetColumn;
  813. DataColumn dstColumn = row.Table.Columns [dstColumnName];
  814. if (dstColumn == null
  815. || (dstColumn.Expression != null
  816. && dstColumn.Expression.Length > 0))
  817. continue;
  818. // info from : http://www.error-bank.com/microsoft.public.dotnet.framework.windowsforms.databinding/
  819. // [email protected]_Thread.aspx
  820. // disable readonly for non-expression columns.
  821. bool readOnlyState = dstColumn.ReadOnly;
  822. dstColumn.ReadOnly = false;
  823. try {
  824. row [dstColumnName] = reader [columnName];
  825. } finally {
  826. dstColumn.ReadOnly = readOnlyState;
  827. }
  828. }
  829. }
  830. }
  831. reader.Close ();
  832. int tmp = reader.RecordsAffected; // records affected is valid only after closing reader
  833. // if the execute does not effect any rows we throw an exception.
  834. if (tmp == 0)
  835. throw new DBConcurrencyException("Concurrency violation: the " +
  836. commandName +"Command affected 0 records.");
  837. updateCount += tmp;
  838. if (command.UpdatedRowSource == UpdateRowSource.Both ||
  839. command.UpdatedRowSource == UpdateRowSource.OutputParameters) {
  840. // Update output parameters to row values
  841. foreach (IDataParameter parameter in command.Parameters) {
  842. if (parameter.Direction != ParameterDirection.InputOutput
  843. && parameter.Direction != ParameterDirection.Output
  844. && parameter.Direction != ParameterDirection.ReturnValue)
  845. continue;
  846. string dsColumnName = parameter.SourceColumn;
  847. if (columnMappings != null &&
  848. columnMappings.Contains(parameter.SourceColumn))
  849. dsColumnName = columnMappings [parameter.SourceColumn].DataSetColumn;
  850. DataColumn dstColumn = row.Table.Columns [dsColumnName];
  851. if (dstColumn == null
  852. || (dstColumn.Expression != null
  853. && dstColumn.Expression.Length > 0))
  854. continue;
  855. bool readOnlyState = dstColumn.ReadOnly;
  856. dstColumn.ReadOnly = false;
  857. try {
  858. row [dsColumnName] = parameter.Value;
  859. } finally {
  860. dstColumn.ReadOnly = readOnlyState;
  861. }
  862. }
  863. }
  864. RowUpdatedEventArgs updatedArgs = CreateRowUpdatedEvent(row, command, statementType, tableMapping);
  865. OnRowUpdated(updatedArgs);
  866. switch(updatedArgs.Status) {
  867. case UpdateStatus.Continue:
  868. break;
  869. case UpdateStatus.ErrorsOccurred:
  870. if (updatedArgs.Errors == null) {
  871. updatedArgs.Errors = ExceptionHelper.RowUpdatedError();
  872. }
  873. row.RowError += updatedArgs.Errors.Message;
  874. if (!ContinueUpdateOnError) {
  875. throw updatedArgs.Errors;
  876. }
  877. break;
  878. case UpdateStatus.SkipCurrentRow:
  879. continue;
  880. case UpdateStatus.SkipAllRemainingRows:
  881. return updateCount;
  882. }
  883. row.AcceptChanges ();
  884. } catch(Exception e) {
  885. row.RowError = e.Message;
  886. if (!ContinueUpdateOnError) {
  887. throw e;
  888. }
  889. } finally {
  890. if (reader != null && ! reader.IsClosed) {
  891. reader.Close ();
  892. }
  893. }
  894. }
  895. return updateCount;
  896. }
  897. public int Update (DataSet dataSet, string sourceTable)
  898. {
  899. MissingMappingAction mappingAction = MissingMappingAction;
  900. if (mappingAction == MissingMappingAction.Ignore)
  901. mappingAction = MissingMappingAction.Error;
  902. DataTableMapping tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction (TableMappings, sourceTable, sourceTable, mappingAction);
  903. DataTable dataTable = dataSet.Tables[tableMapping.DataSetTable];
  904. if (dataTable == null)
  905. throw new ArgumentException (String.Format ("Missing table {0}",
  906. sourceTable));
  907. return Update (dataTable, tableMapping);
  908. }
  909. #if ONLY_1_0 || ONLY_1_1
  910. protected virtual void OnFillError (FillErrorEventArgs value)
  911. {
  912. if (FillError != null)
  913. FillError (this, value);
  914. }
  915. #endif
  916. protected abstract void OnRowUpdated (RowUpdatedEventArgs value);
  917. protected abstract void OnRowUpdating (RowUpdatingEventArgs value);
  918. #endregion // Methods
  919. }
  920. }