DataAdapter.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. //
  2. // System.Data.Common.DataAdapter
  3. //
  4. // Author:
  5. // Rodrigo Moya ([email protected])
  6. // Tim Coleman ([email protected])
  7. //
  8. // (C) Ximian, Inc
  9. // Copyright (C) Tim Coleman, 2002-2003
  10. //
  11. //
  12. // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
  13. //
  14. // Permission is hereby granted, free of charge, to any person obtaining
  15. // a copy of this software and associated documentation files (the
  16. // "Software"), to deal in the Software without restriction, including
  17. // without limitation the rights to use, copy, modify, merge, publish,
  18. // distribute, sublicense, and/or sell copies of the Software, and to
  19. // permit persons to whom the Software is furnished to do so, subject to
  20. // the following conditions:
  21. //
  22. // The above copyright notice and this permission notice shall be
  23. // included in all copies or substantial portions of the Software.
  24. //
  25. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  26. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  27. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  28. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  29. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  30. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  31. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  32. //
  33. using System;
  34. using System.Data;
  35. using System.Collections;
  36. using System.ComponentModel;
  37. namespace System.Data.Common
  38. {
  39. /// <summary>
  40. /// Represents a set of data commands and a database connection that are used to fill the DataSet and update the data source.
  41. /// </summary>
  42. public
  43. class DataAdapter : Component, IDataAdapter
  44. {
  45. #region Fields
  46. private bool acceptChangesDuringFill;
  47. private bool continueUpdateOnError;
  48. private MissingMappingAction missingMappingAction;
  49. private MissingSchemaAction missingSchemaAction;
  50. private DataTableMappingCollection tableMappings;
  51. private const string DefaultSourceTableName = "Table";
  52. private const string DefaultSourceColumnName = "Column";
  53. private bool acceptChangesDuringUpdate;
  54. private LoadOption fillLoadOption;
  55. private bool returnProviderSpecificTypes;
  56. #endregion
  57. #region Constructors
  58. protected DataAdapter ()
  59. {
  60. acceptChangesDuringFill = true;
  61. continueUpdateOnError = false;
  62. missingMappingAction = MissingMappingAction.Passthrough;
  63. missingSchemaAction = MissingSchemaAction.Add;
  64. tableMappings = new DataTableMappingCollection ();
  65. acceptChangesDuringUpdate = true;
  66. fillLoadOption = LoadOption.OverwriteChanges;
  67. returnProviderSpecificTypes = false;
  68. }
  69. protected DataAdapter (DataAdapter from)
  70. {
  71. AcceptChangesDuringFill = from.AcceptChangesDuringFill;
  72. ContinueUpdateOnError = from.ContinueUpdateOnError;
  73. MissingMappingAction = from.MissingMappingAction;
  74. MissingSchemaAction = from.MissingSchemaAction;
  75. if (from.tableMappings != null)
  76. foreach (ICloneable cloneable in from.TableMappings)
  77. TableMappings.Add (cloneable.Clone ());
  78. acceptChangesDuringUpdate = from.AcceptChangesDuringUpdate;
  79. fillLoadOption = from.FillLoadOption;
  80. returnProviderSpecificTypes = from.ReturnProviderSpecificTypes;
  81. }
  82. #endregion
  83. #region Properties
  84. [DataCategory ("Fill")]
  85. [DefaultValue (true)]
  86. public bool AcceptChangesDuringFill {
  87. get { return acceptChangesDuringFill; }
  88. set { acceptChangesDuringFill = value; }
  89. }
  90. [DefaultValue (true)]
  91. public bool AcceptChangesDuringUpdate {
  92. get { return acceptChangesDuringUpdate; }
  93. set { acceptChangesDuringUpdate = value; }
  94. }
  95. [DataCategory ("Update")]
  96. [DefaultValue (false)]
  97. public bool ContinueUpdateOnError {
  98. get { return continueUpdateOnError; }
  99. set { continueUpdateOnError = value; }
  100. }
  101. [RefreshProperties (RefreshProperties.All)]
  102. public LoadOption FillLoadOption {
  103. get { return fillLoadOption; }
  104. set {
  105. ExceptionHelper.CheckEnumValue (typeof (LoadOption), value);
  106. fillLoadOption = value;
  107. }
  108. }
  109. ITableMappingCollection IDataAdapter.TableMappings {
  110. get { return TableMappings; }
  111. }
  112. [DataCategory ("Mapping")]
  113. [DefaultValue (MissingMappingAction.Passthrough)]
  114. public MissingMappingAction MissingMappingAction {
  115. get { return missingMappingAction; }
  116. set {
  117. ExceptionHelper.CheckEnumValue (typeof (MissingMappingAction), value);
  118. missingMappingAction = value;
  119. }
  120. }
  121. [DataCategory ("Mapping")]
  122. [DefaultValue (MissingSchemaAction.Add)]
  123. public MissingSchemaAction MissingSchemaAction {
  124. get { return missingSchemaAction; }
  125. set {
  126. ExceptionHelper.CheckEnumValue (typeof (MissingSchemaAction), value);
  127. missingSchemaAction = value;
  128. }
  129. }
  130. [DefaultValue (false)]
  131. public virtual bool ReturnProviderSpecificTypes {
  132. get { return returnProviderSpecificTypes; }
  133. set { returnProviderSpecificTypes = value; }
  134. }
  135. [DataCategory ("Mapping")]
  136. [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
  137. public DataTableMappingCollection TableMappings {
  138. get { return tableMappings; }
  139. }
  140. #endregion
  141. #region Events
  142. public event FillErrorEventHandler FillError;
  143. #endregion
  144. #region Methods
  145. [Obsolete ("Use the protected constructor instead")]
  146. [MonoTODO]
  147. protected virtual DataAdapter CloneInternals ()
  148. {
  149. throw new NotImplementedException ();
  150. }
  151. protected virtual DataTableMappingCollection CreateTableMappings ()
  152. {
  153. return new DataTableMappingCollection ();
  154. }
  155. [MonoTODO]
  156. protected override void Dispose (bool disposing)
  157. {
  158. }
  159. protected virtual bool ShouldSerializeTableMappings ()
  160. {
  161. return true;
  162. }
  163. internal int FillInternal (DataTable dataTable, IDataReader dataReader)
  164. {
  165. if (dataReader.FieldCount == 0) {
  166. dataReader.Close ();
  167. return 0;
  168. }
  169. int count = 0;
  170. try {
  171. string tableName = SetupSchema (SchemaType.Mapped, dataTable.TableName);
  172. if (tableName != null) {
  173. dataTable.TableName = tableName;
  174. FillTable (dataTable, dataReader, 0, 0, ref count);
  175. }
  176. } finally {
  177. dataReader.Close ();
  178. }
  179. return count;
  180. }
  181. // this method builds the schema for a given datatable. it returns a int array with
  182. // "array[ordinal of datatable column] == index of source column in data reader".
  183. // each column in the datatable has a mapping to a specific column in the datareader,
  184. // the int array represents this match.
  185. internal int[] BuildSchema (IDataReader reader, DataTable table, SchemaType schemaType)
  186. {
  187. return BuildSchema (reader, table, schemaType, MissingSchemaAction,
  188. MissingMappingAction, TableMappings);
  189. }
  190. /// <summary>
  191. /// Creates or Modifies the schema of the given DataTable based on the schema of
  192. /// the reader and the arguments passed.
  193. /// </summary>
  194. internal static int[] BuildSchema (IDataReader reader, DataTable table,
  195. SchemaType schemaType,
  196. MissingSchemaAction missingSchAction,
  197. MissingMappingAction missingMapAction,
  198. DataTableMappingCollection dtMapping
  199. )
  200. {
  201. int readerIndex = 0;
  202. // FIXME : this fails if query has fewer columns than a table
  203. int[] mapping = new int[table.Columns.Count]; // mapping the reader indexes to the datatable indexes
  204. for(int i=0; i < mapping.Length; i++) {
  205. mapping[i] = -1;
  206. }
  207. ArrayList primaryKey = new ArrayList ();
  208. ArrayList sourceColumns = new ArrayList ();
  209. bool createPrimaryKey = true;
  210. DataTable schemaTable = reader.GetSchemaTable ();
  211. DataColumn ColumnNameCol = schemaTable.Columns["ColumnName"];
  212. DataColumn DataTypeCol = schemaTable.Columns["DataType"];
  213. DataColumn IsAutoIncrementCol = schemaTable.Columns["IsAutoIncrement"];
  214. DataColumn AllowDBNullCol = schemaTable.Columns["AllowDBNull"];
  215. DataColumn IsReadOnlyCol = schemaTable.Columns["IsReadOnly"];
  216. DataColumn IsKeyCol = schemaTable.Columns["IsKey"];
  217. DataColumn IsUniqueCol = schemaTable.Columns["IsUnique"];
  218. DataColumn ColumnSizeCol = schemaTable.Columns["ColumnSize"];
  219. foreach (DataRow schemaRow in schemaTable.Rows) {
  220. // generate a unique column name in the source table.
  221. string sourceColumnName;
  222. string realSourceColumnName ;
  223. if (ColumnNameCol == null || schemaRow.IsNull(ColumnNameCol) ||
  224. (string)schemaRow [ColumnNameCol] == String.Empty) {
  225. sourceColumnName = DefaultSourceColumnName;
  226. realSourceColumnName = DefaultSourceColumnName + "1";
  227. } else {
  228. sourceColumnName = (string) schemaRow [ColumnNameCol];
  229. realSourceColumnName = sourceColumnName;
  230. }
  231. for (int i = 1; sourceColumns.Contains (realSourceColumnName); i += 1)
  232. realSourceColumnName = String.Format ("{0}{1}", sourceColumnName, i);
  233. sourceColumns.Add(realSourceColumnName);
  234. // generate DataSetColumnName from DataTableMapping, if any
  235. DataTableMapping tableMapping = null;
  236. //FIXME : The sourcetable name shud get passed as a parameter..
  237. int index = dtMapping.IndexOfDataSetTable (table.TableName);
  238. string srcTable = (index != -1 ? dtMapping[index].SourceTable : table.TableName);
  239. tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction (dtMapping, ADP.IsEmpty (srcTable) ? " " : srcTable, table.TableName, missingMapAction);
  240. if (tableMapping != null) {
  241. table.TableName = tableMapping.DataSetTable;
  242. // check to see if the column mapping exists
  243. DataColumnMapping columnMapping = DataColumnMappingCollection.GetColumnMappingBySchemaAction(tableMapping.ColumnMappings, realSourceColumnName, missingMapAction);
  244. if (columnMapping != null) {
  245. Type columnType = schemaRow[DataTypeCol] as Type;
  246. DataColumn col = columnType != null ? columnMapping.GetDataColumnBySchemaAction(
  247. table ,
  248. columnType,
  249. missingSchAction) : null;
  250. if (col != null) {
  251. // if the column is not in the table - add it.
  252. if (table.Columns.IndexOf(col) == -1) {
  253. if (missingSchAction == MissingSchemaAction.Add
  254. || missingSchAction == MissingSchemaAction.AddWithKey)
  255. table.Columns.Add(col);
  256. int[] tmp = new int[mapping.Length + 1];
  257. Array.Copy(mapping,0,tmp,0,col.Ordinal);
  258. Array.Copy(mapping,col.Ordinal,tmp,col.Ordinal + 1,mapping.Length - col.Ordinal);
  259. mapping = tmp;
  260. }
  261. if (missingSchAction == MissingSchemaAction.AddWithKey) {
  262. object value = (AllowDBNullCol != null) ? schemaRow[AllowDBNullCol] : null;
  263. bool allowDBNull = value is bool ? (bool)value : true;
  264. value = (IsKeyCol != null) ? schemaRow[IsKeyCol] : null;
  265. bool isKey = value is bool ? (bool)value : false;
  266. value = (IsAutoIncrementCol != null) ? schemaRow[IsAutoIncrementCol] : null;
  267. bool isAutoIncrement = value is bool ? (bool)value : false;
  268. value = (IsReadOnlyCol != null) ? schemaRow[IsReadOnlyCol] : null;
  269. bool isReadOnly = value is bool ? (bool)value : false;
  270. value = (IsUniqueCol != null) ? schemaRow[IsUniqueCol] : null;
  271. bool isUnique = value is bool ? (bool)value : false;
  272. col.AllowDBNull = allowDBNull;
  273. // fill woth key info
  274. if (isAutoIncrement && DataColumn.CanAutoIncrement(columnType)) {
  275. col.AutoIncrement = true;
  276. if (!allowDBNull)
  277. col.AllowDBNull = false;
  278. }
  279. if (columnType == DbTypes.TypeOfString) {
  280. col.MaxLength = (ColumnSizeCol != null) ? (int)schemaRow[ColumnSizeCol] : 0;
  281. }
  282. if (isReadOnly)
  283. col.ReadOnly = true;
  284. if (!allowDBNull && (!isReadOnly || isKey))
  285. col.AllowDBNull = false;
  286. if (isUnique && !isKey && !columnType.IsArray) {
  287. col.Unique = true;
  288. if (!allowDBNull)
  289. col.AllowDBNull = false;
  290. }
  291. // This might not be set by all DataProviders
  292. bool isHidden = false;
  293. if (schemaTable.Columns.Contains ("IsHidden")) {
  294. value = schemaRow["IsHidden"];
  295. isHidden = ((value is bool) ? (bool)value : false);
  296. }
  297. if (isKey && !isHidden) {
  298. primaryKey.Add (col);
  299. if (allowDBNull)
  300. createPrimaryKey = false;
  301. }
  302. }
  303. // add the ordinal of the column as a key and the index of the column in the datareader as a value.
  304. mapping[col.Ordinal] = readerIndex++;
  305. }
  306. }
  307. }
  308. }
  309. if (primaryKey.Count > 0) {
  310. DataColumn[] colKey = (DataColumn[])(primaryKey.ToArray(typeof (DataColumn)));
  311. if (createPrimaryKey)
  312. table.PrimaryKey = colKey;
  313. else {
  314. UniqueConstraint uConstraint = new UniqueConstraint(colKey);
  315. for (int i = 0; i < table.Constraints.Count; i++) {
  316. if (table.Constraints[i].Equals(uConstraint)) {
  317. uConstraint = null;
  318. break;
  319. }
  320. }
  321. if (uConstraint != null)
  322. table.Constraints.Add(uConstraint);
  323. }
  324. }
  325. return mapping;
  326. }
  327. internal bool FillTable (DataTable dataTable, IDataReader dataReader, int startRecord, int maxRecords, ref int counter)
  328. {
  329. if (dataReader.FieldCount == 0)
  330. return false;
  331. int counterStart = counter;
  332. int[] mapping = BuildSchema (dataReader, dataTable, SchemaType.Mapped);
  333. int [] sortedMapping = new int [mapping.Length];
  334. int length = sortedMapping.Length;
  335. for (int i = 0; i < sortedMapping.Length; i++) {
  336. if (mapping [i] >= 0)
  337. sortedMapping [mapping [i]] = i;
  338. else
  339. sortedMapping [--length] = i;
  340. }
  341. for (int i = 0; i < startRecord; i++) {
  342. dataReader.Read ();
  343. }
  344. dataTable.BeginLoadData ();
  345. while (dataReader.Read () && (maxRecords == 0 || (counter - counterStart) < maxRecords)) {
  346. try {
  347. dataTable.LoadDataRow (dataReader, sortedMapping, length, AcceptChangesDuringFill);
  348. counter++;
  349. }
  350. catch (Exception e) {
  351. object[] readerArray = new object [dataReader.FieldCount];
  352. object[] tableArray = new object [mapping.Length];
  353. // we get the values from the datareader
  354. dataReader.GetValues (readerArray);
  355. // copy from datareader columns to table columns according to given mapping
  356. for (int i = 0; i < mapping.Length; i++) {
  357. if (mapping [i] >= 0) {
  358. tableArray [i] = readerArray [mapping [i]];
  359. }
  360. }
  361. FillErrorEventArgs args = CreateFillErrorEvent (dataTable, tableArray, e);
  362. OnFillErrorInternal (args);
  363. // if args.Continue is not set to true or if a handler is not set, rethrow the error..
  364. if(!args.Continue)
  365. throw e;
  366. }
  367. }
  368. dataTable.EndLoadData ();
  369. return true;
  370. }
  371. internal virtual void OnFillErrorInternal (FillErrorEventArgs value)
  372. {
  373. OnFillError (value);
  374. }
  375. internal FillErrorEventArgs CreateFillErrorEvent (DataTable dataTable, object[] values, Exception e)
  376. {
  377. FillErrorEventArgs args = new FillErrorEventArgs (dataTable, values);
  378. args.Errors = e;
  379. args.Continue = false;
  380. return args;
  381. }
  382. internal string SetupSchema (SchemaType schemaType, string sourceTableName)
  383. {
  384. DataTableMapping tableMapping = null;
  385. if (schemaType == SchemaType.Mapped) {
  386. tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction (TableMappings, sourceTableName, sourceTableName, MissingMappingAction);
  387. if (tableMapping != null)
  388. return tableMapping.DataSetTable;
  389. return null;
  390. } else
  391. return sourceTableName;
  392. }
  393. internal int FillInternal (DataSet dataSet, string srcTable, IDataReader dataReader, int startRecord, int maxRecords)
  394. {
  395. if (dataSet == null)
  396. throw new ArgumentNullException ("DataSet");
  397. if (startRecord < 0)
  398. throw new ArgumentException ("The startRecord parameter was less than 0.");
  399. if (maxRecords < 0)
  400. throw new ArgumentException ("The maxRecords parameter was less than 0.");
  401. DataTable dataTable = null;
  402. int resultIndex = 0;
  403. int count = 0;
  404. try {
  405. string tableName = srcTable;
  406. do {
  407. // Non-resultset queries like insert, delete or update aren't processed.
  408. if (dataReader.FieldCount != -1) {
  409. tableName = SetupSchema (SchemaType.Mapped, tableName);
  410. if (tableName != null) {
  411. // check if the table exists in the dataset
  412. if (dataSet.Tables.Contains (tableName))
  413. // get the table from the dataset
  414. dataTable = dataSet.Tables [tableName];
  415. else {
  416. // Do not create schema if MissingSchemAction is set to Ignore
  417. if (this.MissingSchemaAction == MissingSchemaAction.Ignore)
  418. continue;
  419. dataTable = dataSet.Tables.Add (tableName);
  420. }
  421. if (!FillTable (dataTable, dataReader, startRecord, maxRecords, ref count))
  422. continue;
  423. tableName = String.Format ("{0}{1}", srcTable, ++resultIndex);
  424. startRecord = 0;
  425. maxRecords = 0;
  426. }
  427. }
  428. } while (dataReader.NextResult ());
  429. } finally {
  430. dataReader.Close ();
  431. }
  432. return count;
  433. }
  434. public virtual int Fill (DataSet dataSet)
  435. {
  436. throw new NotSupportedException();
  437. }
  438. protected virtual int Fill (DataTable dataTable, IDataReader dataReader)
  439. {
  440. return FillInternal (dataTable, dataReader);
  441. }
  442. protected virtual int Fill (DataTable[] dataTables, IDataReader dataReader, int startRecord, int maxRecords)
  443. {
  444. int count = 0;
  445. if (dataReader.IsClosed)
  446. return 0;
  447. if (startRecord < 0)
  448. throw new ArgumentException ("The startRecord parameter was less than 0.");
  449. if (maxRecords < 0)
  450. throw new ArgumentException ("The maxRecords parameter was less than 0.");
  451. try {
  452. foreach (DataTable dataTable in dataTables) {
  453. string tableName = SetupSchema (SchemaType.Mapped, dataTable.TableName);
  454. if (tableName != null) {
  455. dataTable.TableName = tableName;
  456. FillTable (dataTable, dataReader, 0, 0, ref count);
  457. }
  458. }
  459. } finally {
  460. dataReader.Close ();
  461. }
  462. return count;
  463. }
  464. protected virtual int Fill (DataSet dataSet, string srcTable, IDataReader dataReader, int startRecord, int maxRecords)
  465. {
  466. return FillInternal (dataSet, srcTable, dataReader, startRecord, maxRecords);
  467. }
  468. [MonoTODO]
  469. protected virtual DataTable FillSchema (DataTable dataTable, SchemaType schemaType, IDataReader dataReader)
  470. {
  471. throw new NotImplementedException ();
  472. }
  473. [MonoTODO]
  474. protected virtual DataTable[] FillSchema (DataSet dataSet, SchemaType schemaType, string srcTable, IDataReader dataReader)
  475. {
  476. throw new NotImplementedException ();
  477. }
  478. public virtual DataTable[] FillSchema (DataSet dataSet, SchemaType schemaType)
  479. {
  480. throw new NotSupportedException ();
  481. }
  482. [MonoTODO]
  483. [EditorBrowsable (EditorBrowsableState.Advanced)]
  484. public virtual IDataParameter[] GetFillParameters ()
  485. {
  486. throw new NotImplementedException ();
  487. }
  488. protected bool HasTableMappings ()
  489. {
  490. return (TableMappings.Count != 0);
  491. }
  492. protected virtual void OnFillError (FillErrorEventArgs value)
  493. {
  494. if (FillError != null)
  495. FillError (this, value);
  496. }
  497. [EditorBrowsable (EditorBrowsableState.Never)]
  498. public void ResetFillLoadOption ()
  499. {
  500. //FIXME: what else ??
  501. FillLoadOption = LoadOption.OverwriteChanges;
  502. }
  503. [EditorBrowsable (EditorBrowsableState.Never)]
  504. public virtual bool ShouldSerializeAcceptChangesDuringFill ()
  505. {
  506. return true;
  507. }
  508. [EditorBrowsable (EditorBrowsableState.Never)]
  509. public virtual bool ShouldSerializeFillLoadOption ()
  510. {
  511. return false;
  512. }
  513. [MonoTODO]
  514. public virtual int Update (DataSet dataSet)
  515. {
  516. throw new NotImplementedException ();
  517. }
  518. #endregion
  519. }
  520. }