DbDataAdapter.cs 35 KB

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