SqlDataAdapter.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. //
  2. // System.Data.SqlClient.SqlDataAdapter.cs
  3. //
  4. // Author:
  5. // Rodrigo Moya ([email protected])
  6. // Daniel Morgan ([email protected])
  7. // Tim Coleman ([email protected])
  8. // Veerapuram Varadhan ([email protected])
  9. //
  10. // (C) Ximian, Inc 2002
  11. // Copyright (C) 2002 Tim Coleman
  12. //
  13. // Copyright (C) 2004, 2009 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.Data.Common;
  39. namespace System.Data.SqlClient {
  40. [DefaultEvent ("RowUpdated")]
  41. [DesignerAttribute ("Microsoft.VSDesigner.Data.VS.SqlDataAdapterDesigner, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.ComponentModel.Design.IDesigner")]
  42. [ToolboxItemAttribute ("Microsoft.VSDesigner.Data.VS.SqlDataAdapterToolboxItem, "+ Consts.AssemblyMicrosoft_VSDesigner)]
  43. public sealed class SqlDataAdapter : DbDataAdapter, IDbDataAdapter, IDataAdapter, ICloneable
  44. {
  45. #region Copy from old DataColumn
  46. internal static bool CanAutoIncrement (Type type)
  47. {
  48. switch (Type.GetTypeCode (type)) {
  49. case TypeCode.Int16:
  50. case TypeCode.Int32:
  51. case TypeCode.Int64:
  52. case TypeCode.Decimal:
  53. return true;
  54. }
  55. return false;
  56. }
  57. #endregion
  58. #region Copy from old DataAdapter
  59. private const string DefaultSourceColumnName = "Column";
  60. internal FillErrorEventArgs CreateFillErrorEvent (DataTable dataTable, object[] values, Exception e)
  61. {
  62. FillErrorEventArgs args = new FillErrorEventArgs (dataTable, values);
  63. args.Errors = e;
  64. args.Continue = false;
  65. return args;
  66. }
  67. internal void OnFillErrorInternal (FillErrorEventArgs value)
  68. {
  69. OnFillError (value);
  70. }
  71. // this method builds the schema for a given datatable. it returns a int array with
  72. // "array[ordinal of datatable column] == index of source column in data reader".
  73. // each column in the datatable has a mapping to a specific column in the datareader,
  74. // the int array represents this match.
  75. internal int[] BuildSchema (IDataReader reader, DataTable table, SchemaType schemaType)
  76. {
  77. return BuildSchema (reader, table, schemaType, MissingSchemaAction,
  78. MissingMappingAction, TableMappings);
  79. }
  80. /// <summary>
  81. /// Creates or Modifies the schema of the given DataTable based on the schema of
  82. /// the reader and the arguments passed.
  83. /// </summary>
  84. internal static int[] BuildSchema (IDataReader reader, DataTable table,
  85. SchemaType schemaType,
  86. MissingSchemaAction missingSchAction,
  87. MissingMappingAction missingMapAction,
  88. DataTableMappingCollection dtMapping
  89. )
  90. {
  91. int readerIndex = 0;
  92. // FIXME : this fails if query has fewer columns than a table
  93. int[] mapping = new int[table.Columns.Count]; // mapping the reader indexes to the datatable indexes
  94. for(int i=0; i < mapping.Length; i++) {
  95. mapping[i] = -1;
  96. }
  97. ArrayList primaryKey = new ArrayList ();
  98. ArrayList sourceColumns = new ArrayList ();
  99. bool createPrimaryKey = true;
  100. DataTable schemaTable = reader.GetSchemaTable ();
  101. DataColumn ColumnNameCol = schemaTable.Columns["ColumnName"];
  102. DataColumn DataTypeCol = schemaTable.Columns["DataType"];
  103. DataColumn IsAutoIncrementCol = schemaTable.Columns["IsAutoIncrement"];
  104. DataColumn AllowDBNullCol = schemaTable.Columns["AllowDBNull"];
  105. DataColumn IsReadOnlyCol = schemaTable.Columns["IsReadOnly"];
  106. DataColumn IsKeyCol = schemaTable.Columns["IsKey"];
  107. DataColumn IsUniqueCol = schemaTable.Columns["IsUnique"];
  108. DataColumn ColumnSizeCol = schemaTable.Columns["ColumnSize"];
  109. foreach (DataRow schemaRow in schemaTable.Rows) {
  110. // generate a unique column name in the source table.
  111. string sourceColumnName;
  112. string realSourceColumnName ;
  113. if (ColumnNameCol == null || schemaRow.IsNull(ColumnNameCol) ||
  114. (string)schemaRow [ColumnNameCol] == String.Empty) {
  115. sourceColumnName = DefaultSourceColumnName;
  116. realSourceColumnName = DefaultSourceColumnName + "1";
  117. } else {
  118. sourceColumnName = (string) schemaRow [ColumnNameCol];
  119. realSourceColumnName = sourceColumnName;
  120. }
  121. for (int i = 1; sourceColumns.Contains (realSourceColumnName); i += 1)
  122. realSourceColumnName = String.Format ("{0}{1}", sourceColumnName, i);
  123. sourceColumns.Add(realSourceColumnName);
  124. // generate DataSetColumnName from DataTableMapping, if any
  125. DataTableMapping tableMapping = null;
  126. //FIXME : The sourcetable name shud get passed as a parameter..
  127. int index = dtMapping.IndexOfDataSetTable (table.TableName);
  128. string srcTable = (index != -1 ? dtMapping[index].SourceTable : table.TableName);
  129. tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction (dtMapping, ADP.IsEmpty (srcTable) ? " " : srcTable, table.TableName, missingMapAction);
  130. if (tableMapping != null) {
  131. table.TableName = tableMapping.DataSetTable;
  132. // check to see if the column mapping exists
  133. DataColumnMapping columnMapping = DataColumnMappingCollection.GetColumnMappingBySchemaAction(tableMapping.ColumnMappings, realSourceColumnName, missingMapAction);
  134. if (columnMapping != null) {
  135. Type columnType = schemaRow[DataTypeCol] as Type;
  136. DataColumn col = columnType != null ? columnMapping.GetDataColumnBySchemaAction(
  137. table ,
  138. columnType,
  139. missingSchAction) : null;
  140. if (col != null) {
  141. // if the column is not in the table - add it.
  142. if (table.Columns.IndexOf(col) == -1) {
  143. if (missingSchAction == MissingSchemaAction.Add
  144. || missingSchAction == MissingSchemaAction.AddWithKey)
  145. table.Columns.Add(col);
  146. int[] tmp = new int[mapping.Length + 1];
  147. Array.Copy(mapping,0,tmp,0,col.Ordinal);
  148. Array.Copy(mapping,col.Ordinal,tmp,col.Ordinal + 1,mapping.Length - col.Ordinal);
  149. mapping = tmp;
  150. }
  151. if (missingSchAction == MissingSchemaAction.AddWithKey) {
  152. object value = (AllowDBNullCol != null) ? schemaRow[AllowDBNullCol] : null;
  153. bool allowDBNull = value is bool ? (bool)value : true;
  154. value = (IsKeyCol != null) ? schemaRow[IsKeyCol] : null;
  155. bool isKey = value is bool ? (bool)value : false;
  156. value = (IsAutoIncrementCol != null) ? schemaRow[IsAutoIncrementCol] : null;
  157. bool isAutoIncrement = value is bool ? (bool)value : false;
  158. value = (IsReadOnlyCol != null) ? schemaRow[IsReadOnlyCol] : null;
  159. bool isReadOnly = value is bool ? (bool)value : false;
  160. value = (IsUniqueCol != null) ? schemaRow[IsUniqueCol] : null;
  161. bool isUnique = value is bool ? (bool)value : false;
  162. col.AllowDBNull = allowDBNull;
  163. // fill woth key info
  164. if (isAutoIncrement && CanAutoIncrement(columnType)) {
  165. col.AutoIncrement = true;
  166. if (!allowDBNull)
  167. col.AllowDBNull = false;
  168. }
  169. if (columnType == DbTypes.TypeOfString) {
  170. col.MaxLength = (ColumnSizeCol != null) ? (int)schemaRow[ColumnSizeCol] : 0;
  171. }
  172. if (isReadOnly)
  173. col.ReadOnly = true;
  174. if (!allowDBNull && (!isReadOnly || isKey))
  175. col.AllowDBNull = false;
  176. if (isUnique && !isKey && !columnType.IsArray) {
  177. col.Unique = true;
  178. if (!allowDBNull)
  179. col.AllowDBNull = false;
  180. }
  181. // This might not be set by all DataProviders
  182. bool isHidden = false;
  183. if (schemaTable.Columns.Contains ("IsHidden")) {
  184. value = schemaRow["IsHidden"];
  185. isHidden = ((value is bool) ? (bool)value : false);
  186. }
  187. if (isKey && !isHidden) {
  188. primaryKey.Add (col);
  189. if (allowDBNull)
  190. createPrimaryKey = false;
  191. }
  192. }
  193. // add the ordinal of the column as a key and the index of the column in the datareader as a value.
  194. mapping[col.Ordinal] = readerIndex++;
  195. }
  196. }
  197. }
  198. }
  199. if (primaryKey.Count > 0) {
  200. DataColumn[] colKey = (DataColumn[])(primaryKey.ToArray(typeof (DataColumn)));
  201. if (createPrimaryKey)
  202. table.PrimaryKey = colKey;
  203. else {
  204. UniqueConstraint uConstraint = new UniqueConstraint(colKey);
  205. for (int i = 0; i < table.Constraints.Count; i++) {
  206. if (table.Constraints[i].Equals(uConstraint)) {
  207. uConstraint = null;
  208. break;
  209. }
  210. }
  211. if (uConstraint != null)
  212. table.Constraints.Add(uConstraint);
  213. }
  214. }
  215. return mapping;
  216. }
  217. internal int FillInternal (DataTable dataTable, IDataReader dataReader)
  218. {
  219. if (dataReader.FieldCount == 0) {
  220. dataReader.Close ();
  221. return 0;
  222. }
  223. int count = 0;
  224. try {
  225. string tableName = SetupSchema (SchemaType.Mapped, dataTable.TableName);
  226. if (tableName != null) {
  227. dataTable.TableName = tableName;
  228. FillTable (dataTable, dataReader, 0, 0, ref count);
  229. }
  230. } finally {
  231. dataReader.Close ();
  232. }
  233. return count;
  234. }
  235. internal bool FillTable (DataTable dataTable, IDataReader dataReader, int startRecord, int maxRecords, ref int counter)
  236. {
  237. if (dataReader.FieldCount == 0)
  238. return false;
  239. int counterStart = counter;
  240. int[] mapping = BuildSchema (dataReader, dataTable, SchemaType.Mapped);
  241. int [] sortedMapping = new int [mapping.Length];
  242. int length = sortedMapping.Length;
  243. for (int i = 0; i < sortedMapping.Length; i++) {
  244. if (mapping [i] >= 0)
  245. sortedMapping [mapping [i]] = i;
  246. else
  247. sortedMapping [--length] = i;
  248. }
  249. for (int i = 0; i < startRecord; i++) {
  250. dataReader.Read ();
  251. }
  252. dataTable.BeginLoadData ();
  253. object [] values = new object [length];
  254. while (dataReader.Read () && (maxRecords == 0 || (counter - counterStart) < maxRecords)) {
  255. try {
  256. for (int iColumn = 0; iColumn < values.Length; iColumn++)
  257. values [iColumn] = dataReader [iColumn];
  258. dataTable.LoadDataRow (values, AcceptChangesDuringFill);
  259. counter++;
  260. }
  261. catch (Exception e) {
  262. object[] readerArray = new object [dataReader.FieldCount];
  263. object[] tableArray = new object [mapping.Length];
  264. // we get the values from the datareader
  265. dataReader.GetValues (readerArray);
  266. // copy from datareader columns to table columns according to given mapping
  267. for (int i = 0; i < mapping.Length; i++) {
  268. if (mapping [i] >= 0) {
  269. tableArray [i] = readerArray [mapping [i]];
  270. }
  271. }
  272. FillErrorEventArgs args = CreateFillErrorEvent (dataTable, tableArray, e);
  273. OnFillErrorInternal (args);
  274. // if args.Continue is not set to true or if a handler is not set, rethrow the error..
  275. if(!args.Continue)
  276. throw e;
  277. }
  278. }
  279. dataTable.EndLoadData ();
  280. return true;
  281. }
  282. internal string SetupSchema (SchemaType schemaType, string sourceTableName)
  283. {
  284. DataTableMapping tableMapping = null;
  285. if (schemaType == SchemaType.Mapped) {
  286. tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction (TableMappings, sourceTableName, sourceTableName, MissingMappingAction);
  287. if (tableMapping != null)
  288. return tableMapping.DataSetTable;
  289. return null;
  290. } else
  291. return sourceTableName;
  292. }
  293. #endregion
  294. #region Fields
  295. int updateBatchSize;
  296. #endregion
  297. #region Constructors
  298. public SqlDataAdapter () : this ((SqlCommand) null)
  299. {
  300. }
  301. public SqlDataAdapter (SqlCommand selectCommand)
  302. {
  303. SelectCommand = selectCommand;
  304. UpdateBatchSize = 1;
  305. }
  306. public SqlDataAdapter (string selectCommandText, SqlConnection selectConnection)
  307. : this (new SqlCommand (selectCommandText, selectConnection))
  308. {
  309. }
  310. public SqlDataAdapter (string selectCommandText, string selectConnectionString)
  311. : this (selectCommandText, new SqlConnection (selectConnectionString))
  312. {
  313. }
  314. #endregion
  315. #region Properties
  316. [DefaultValue (null)]
  317. [EditorAttribute ("Microsoft.VSDesigner.Data.Design.DBCommandEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
  318. public new SqlCommand DeleteCommand { get; set; }
  319. [DefaultValue (null)]
  320. [EditorAttribute ("Microsoft.VSDesigner.Data.Design.DBCommandEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
  321. public new SqlCommand InsertCommand { get; set; }
  322. [DefaultValue (null)]
  323. [EditorAttribute ("Microsoft.VSDesigner.Data.Design.DBCommandEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
  324. public new SqlCommand SelectCommand { get; set; }
  325. [DefaultValue (null)]
  326. [EditorAttribute ("Microsoft.VSDesigner.Data.Design.DBCommandEditor, "+ Consts.AssemblyMicrosoft_VSDesigner, "System.Drawing.Design.UITypeEditor, "+ Consts.AssemblySystem_Drawing )]
  327. public new SqlCommand UpdateCommand { get; set; }
  328. IDbCommand IDbDataAdapter.SelectCommand {
  329. get { return SelectCommand; }
  330. set { SelectCommand = (SqlCommand) value; }
  331. }
  332. IDbCommand IDbDataAdapter.InsertCommand {
  333. get { return InsertCommand; }
  334. set { InsertCommand = (SqlCommand) value; }
  335. }
  336. IDbCommand IDbDataAdapter.UpdateCommand {
  337. get { return UpdateCommand; }
  338. set { UpdateCommand = (SqlCommand) value; }
  339. }
  340. IDbCommand IDbDataAdapter.DeleteCommand {
  341. get { return DeleteCommand; }
  342. set { DeleteCommand = (SqlCommand) value; }
  343. }
  344. public override int UpdateBatchSize {
  345. get { return updateBatchSize; }
  346. set {
  347. if (value < 0)
  348. throw new ArgumentOutOfRangeException ("UpdateBatchSize");
  349. updateBatchSize = value;
  350. }
  351. }
  352. #endregion // Properties
  353. #region Methods
  354. protected override RowUpdatedEventArgs CreateRowUpdatedEvent (DataRow dataRow, IDbCommand command, StatementType statementType, DataTableMapping tableMapping)
  355. {
  356. return new SqlRowUpdatedEventArgs (dataRow, command, statementType, tableMapping);
  357. }
  358. protected override RowUpdatingEventArgs CreateRowUpdatingEvent (DataRow dataRow, IDbCommand command, StatementType statementType, DataTableMapping tableMapping)
  359. {
  360. return new SqlRowUpdatingEventArgs (dataRow, command, statementType, tableMapping);
  361. }
  362. protected override void OnRowUpdated (RowUpdatedEventArgs value)
  363. {
  364. if (RowUpdated != null)
  365. RowUpdated (this, (SqlRowUpdatedEventArgs) value);
  366. }
  367. protected override void OnRowUpdating (RowUpdatingEventArgs value)
  368. {
  369. if (RowUpdating != null)
  370. RowUpdating (this, (SqlRowUpdatingEventArgs) value);
  371. }
  372. [MonoTODO]
  373. object ICloneable.Clone()
  374. {
  375. throw new NotImplementedException ();
  376. }
  377. // All the batch methods, should be implemented, if supported,
  378. // by individual providers
  379. [MonoTODO]
  380. protected override int AddToBatch (IDbCommand command)
  381. {
  382. throw new NotImplementedException ();
  383. }
  384. [MonoTODO]
  385. protected override void ClearBatch ()
  386. {
  387. throw new NotImplementedException ();
  388. }
  389. [MonoTODO]
  390. protected override int ExecuteBatch ()
  391. {
  392. throw new NotImplementedException ();
  393. }
  394. [MonoTODO]
  395. protected override IDataParameter GetBatchedParameter (int commandIdentifier, int parameterIndex)
  396. {
  397. throw new NotImplementedException ();
  398. }
  399. [MonoTODO]
  400. protected override void InitializeBatching ()
  401. {
  402. throw new NotImplementedException ();
  403. }
  404. [MonoTODO]
  405. protected override void TerminateBatching ()
  406. {
  407. throw new NotImplementedException ();
  408. }
  409. #endregion // Methods
  410. #region Events and Delegates
  411. public event SqlRowUpdatedEventHandler RowUpdated;
  412. public event SqlRowUpdatingEventHandler RowUpdating;
  413. #endregion // Events and Delegates
  414. }
  415. }