2
0

DbDataAdapter.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. //
  2. // System.Data.Common.DbDataAdapter.cs
  3. //
  4. // Author:
  5. // Rodrigo Moya ([email protected])
  6. // Tim Coleman ([email protected])
  7. //
  8. // (C) Ximian, Inc
  9. // Copyright (C) 2002 Tim Coleman
  10. //
  11. using System;
  12. using System.Collections;
  13. using System.ComponentModel;
  14. using System.Data;
  15. namespace System.Data.Common {
  16. public abstract class DbDataAdapter : DataAdapter, ICloneable
  17. {
  18. #region Fields
  19. public const string DefaultSourceTableName = "Table";
  20. const string DefaultSourceColumnName = "Column";
  21. #endregion // Fields
  22. #region Constructors
  23. protected DbDataAdapter()
  24. {
  25. }
  26. #endregion // Fields
  27. #region Properties
  28. IDbCommand DeleteCommand {
  29. get { return ((IDbDataAdapter) this).DeleteCommand; }
  30. }
  31. IDbCommand InsertCommand {
  32. get { return ((IDbDataAdapter) this).InsertCommand; }
  33. }
  34. IDbCommand SelectCommand {
  35. get { return ((IDbDataAdapter) this).SelectCommand; }
  36. }
  37. IDbCommand UpdateCommand {
  38. get { return ((IDbDataAdapter) this).UpdateCommand; }
  39. }
  40. #endregion // Properties
  41. #region Events
  42. [DataCategory ("Fill")]
  43. [DataSysDescription ("Event triggered when a recoverable error occurs during Fill.")]
  44. public event FillErrorEventHandler FillError;
  45. #endregion // Events
  46. #region Methods
  47. protected abstract RowUpdatedEventArgs CreateRowUpdatedEvent (DataRow dataRow, IDbCommand command, StatementType statementType, DataTableMapping tableMapping);
  48. protected abstract RowUpdatingEventArgs CreateRowUpdatingEvent (DataRow dataRow, IDbCommand command, StatementType statementType, DataTableMapping tableMapping);
  49. private FillErrorEventArgs CreateFillErrorEvent (DataTable dataTable, object[] values, Exception e)
  50. {
  51. FillErrorEventArgs args = new FillErrorEventArgs (dataTable, values);
  52. args.Errors = e;
  53. args.Continue = false;
  54. return args;
  55. }
  56. [MonoTODO]
  57. protected override void Dispose (bool disposing)
  58. {
  59. }
  60. public override int Fill (DataSet dataSet)
  61. {
  62. return Fill (dataSet, 0, 0, DefaultSourceTableName, SelectCommand, CommandBehavior.Default);
  63. }
  64. public int Fill (DataTable dataTable)
  65. {
  66. if (dataTable == null)
  67. throw new NullReferenceException ();
  68. return Fill (dataTable, SelectCommand, CommandBehavior.Default);
  69. }
  70. public int Fill (DataSet dataSet, string srcTable)
  71. {
  72. return Fill (dataSet, 0, 0, srcTable, SelectCommand, CommandBehavior.Default);
  73. }
  74. [MonoTODO ("Support filling after we have already filled.")]
  75. protected virtual int Fill (DataTable dataTable, IDataReader dataReader)
  76. {
  77. int count = 0;
  78. bool doContinue = true;
  79. object[] itemArray = new object [dataReader.FieldCount];
  80. SetupSchema (SchemaType.Mapped, dataTable.TableName, dataTable); // FIXME
  81. BuildSchema (dataReader, dataTable, SchemaType.Mapped);
  82. while (doContinue && dataReader.Read ()) {
  83. dataReader.GetValues (itemArray);
  84. try {
  85. dataTable.BeginLoadData ();
  86. dataTable.LoadDataRow (itemArray, AcceptChangesDuringFill);
  87. dataTable.EndLoadData ();
  88. count += 1;
  89. }
  90. catch (Exception e) {
  91. FillErrorEventArgs args = CreateFillErrorEvent (dataTable, itemArray, e);
  92. OnFillError (args);
  93. doContinue = args.Continue;
  94. }
  95. }
  96. dataReader.Close ();
  97. return count;
  98. }
  99. protected virtual int Fill (DataTable dataTable, IDbCommand command, CommandBehavior behavior)
  100. {
  101. return Fill (dataTable, command.ExecuteReader (behavior));
  102. }
  103. public int Fill (DataSet dataSet, int startRecord, int maxRecords, string srcTable)
  104. {
  105. return this.Fill (dataSet, startRecord, maxRecords, srcTable, SelectCommand, CommandBehavior.Default);
  106. }
  107. [MonoTODO ("Support filling after we have already filled.")]
  108. protected virtual int Fill (DataSet dataSet, string srcTable, IDataReader dataReader, int startRecord, int maxRecords)
  109. {
  110. if (startRecord < 0)
  111. throw new ArgumentException ("The startRecord parameter was less than 0.");
  112. if (maxRecords < 0)
  113. throw new ArgumentException ("The maxRecords parameter was less than 0.");
  114. DataTable dataTable;
  115. int resultIndex = 0;
  116. int count = 0;
  117. bool doContinue = true;
  118. string tableName = srcTable;
  119. object[] itemArray = new object [dataReader.FieldCount];
  120. do {
  121. dataTable = new DataTable ();
  122. SetupSchema (SchemaType.Mapped, tableName, dataTable);
  123. if (dataSet.Tables.Contains (dataTable.TableName))
  124. dataTable = dataSet.Tables [tableName];
  125. BuildSchema (dataReader, dataTable, SchemaType.Mapped);
  126. for (int i = 0; i < startRecord; i += 1)
  127. dataReader.Read ();
  128. while (doContinue && dataReader.Read () && !(maxRecords > 0 && count >= maxRecords)) {
  129. dataReader.GetValues (itemArray);
  130. try {
  131. dataTable.BeginLoadData ();
  132. dataTable.LoadDataRow (itemArray, AcceptChangesDuringFill);
  133. dataTable.EndLoadData ();
  134. count += 1;
  135. }
  136. catch (Exception e) {
  137. FillErrorEventArgs args = CreateFillErrorEvent (dataTable, itemArray, e);
  138. OnFillError (args);
  139. doContinue = args.Continue;
  140. }
  141. }
  142. if (dataTable.Rows.Count > 0) {
  143. dataSet.Tables.Add (dataTable);
  144. tableName = String.Format ("{0}{1}", srcTable, ++resultIndex);
  145. }
  146. startRecord = 0;
  147. maxRecords = 0;
  148. } while (doContinue && dataReader.NextResult ());
  149. dataReader.Close ();
  150. return count;
  151. }
  152. protected virtual int Fill (DataSet dataSet, int startRecord, int maxRecords, string srcTable, IDbCommand command, CommandBehavior behavior)
  153. {
  154. CommandBehavior commandBehavior = behavior;
  155. if (command.Connection.State == ConnectionState.Closed) {
  156. command.Connection.Open ();
  157. commandBehavior |= CommandBehavior.CloseConnection;
  158. }
  159. return Fill (dataSet, srcTable, command.ExecuteReader (commandBehavior), startRecord, maxRecords);
  160. }
  161. public override DataTable[] FillSchema (DataSet dataSet, SchemaType schemaType)
  162. {
  163. return FillSchema (dataSet, schemaType, SelectCommand, DefaultSourceTableName, CommandBehavior.Default);
  164. }
  165. public DataTable FillSchema (DataTable dataTable, SchemaType schemaType)
  166. {
  167. return FillSchema (dataTable, schemaType, SelectCommand, CommandBehavior.Default);
  168. }
  169. public DataTable[] FillSchema (DataSet dataSet, SchemaType schemaType, string srcTable)
  170. {
  171. return FillSchema (dataSet, schemaType, SelectCommand, srcTable, CommandBehavior.Default);
  172. }
  173. [MonoTODO ("Verify")]
  174. protected virtual DataTable FillSchema (DataTable dataTable, SchemaType schemaType, IDbCommand command, CommandBehavior behavior)
  175. {
  176. DataTable table;
  177. behavior |= CommandBehavior.SchemaOnly | CommandBehavior.KeyInfo;
  178. if (command.Connection.State == ConnectionState.Closed) {
  179. command.Connection.Open ();
  180. behavior |= CommandBehavior.CloseConnection;
  181. }
  182. IDataReader reader = command.ExecuteReader (behavior);
  183. table = new DataTable ();
  184. SetupSchema (schemaType, DefaultSourceTableName, table);
  185. BuildSchema (reader, table, schemaType);
  186. reader.Close ();
  187. return table;
  188. }
  189. [MonoTODO ("Verify")]
  190. protected virtual DataTable[] FillSchema (DataSet dataSet, SchemaType schemaType, IDbCommand command, string srcTable, CommandBehavior behavior)
  191. {
  192. behavior |= CommandBehavior.SchemaOnly | CommandBehavior.KeyInfo;
  193. if (command.Connection.State == ConnectionState.Closed) {
  194. command.Connection.Open ();
  195. behavior |= CommandBehavior.CloseConnection;
  196. }
  197. IDataReader reader = command.ExecuteReader (behavior);
  198. ArrayList output = new ArrayList ();
  199. string tableName = srcTable;
  200. int index = 0;
  201. do {
  202. DataTable table = new DataTable ();
  203. SetupSchema (schemaType, tableName, table);
  204. if (dataSet.Tables.Contains (table.TableName))
  205. table = dataSet.Tables [table.TableName];
  206. else
  207. dataSet.Tables.Add (table);
  208. BuildSchema (reader, table, schemaType);
  209. output.Add (table);
  210. tableName = String.Format ("{0}{1}", srcTable, ++index);
  211. } while (reader.NextResult ());
  212. reader.Close ();
  213. return (DataTable[]) output.ToArray (typeof (DataTable));
  214. }
  215. private void SetupSchema (SchemaType schemaType, string sourceTableName, DataTable table)
  216. {
  217. DataTableMapping tableMapping = null;
  218. if (schemaType == SchemaType.Mapped)
  219. tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction (TableMappings, sourceTableName, "", MissingMappingAction.Ignore);
  220. if (tableMapping != null)
  221. table.TableName = tableMapping.DataSetTable;
  222. else
  223. table.TableName = sourceTableName;
  224. }
  225. [EditorBrowsable (EditorBrowsableState.Advanced)]
  226. public override IDataParameter[] GetFillParameters ()
  227. {
  228. object[] parameters = new object [SelectCommand.Parameters.Count];
  229. SelectCommand.Parameters.CopyTo (parameters, 0);
  230. return (IDataParameter[]) parameters;
  231. }
  232. [MonoTODO ("Test")]
  233. private void BuildSchema (IDataReader reader, DataTable table, SchemaType schemaType)
  234. {
  235. string sourceColumnName;
  236. string sourceTableName;
  237. string dsColumnName;
  238. ArrayList primaryKey = new ArrayList ();
  239. table.Columns.Clear ();
  240. foreach (DataRow schemaRow in reader.GetSchemaTable ().Rows) {
  241. // generate a unique column name in the dataset table.
  242. if (schemaRow ["BaseColumnName"].Equals (DBNull.Value))
  243. sourceColumnName = DefaultSourceColumnName;
  244. else
  245. sourceColumnName = (string) schemaRow ["BaseColumnName"];
  246. dsColumnName = sourceColumnName;
  247. for (int i = 1; table.Columns.Contains (dsColumnName); i += 1)
  248. dsColumnName = String.Format ("{0}{1}", sourceColumnName, i);
  249. if (schemaRow ["BaseTableName"].Equals (DBNull.Value))
  250. sourceTableName = table.TableName;
  251. else
  252. sourceTableName = (string) schemaRow ["BaseTableName"];
  253. DataTableMapping tableMapping = null;
  254. if (schemaType == SchemaType.Mapped)
  255. tableMapping = DataTableMappingCollection.GetTableMappingBySchemaAction (TableMappings, sourceTableName, table.TableName, MissingMappingAction.Ignore);
  256. if (tableMapping != null) {
  257. table.TableName = tableMapping.DataSetTable;
  258. // check to see if the column mapping exists
  259. if (tableMapping.ColumnMappings.IndexOfDataSetColumn (dsColumnName) < 0) {
  260. if (MissingSchemaAction == MissingSchemaAction.Error)
  261. throw new SystemException ();
  262. tableMapping.ColumnMappings.Add (sourceColumnName, dsColumnName);
  263. }
  264. if (!TableMappings.Contains (tableMapping))
  265. TableMappings.Add (tableMapping);
  266. }
  267. table.Columns.Add (dsColumnName, (Type) schemaRow ["DataType"]);
  268. if (!schemaRow["IsKey"].Equals (DBNull.Value))
  269. if ((bool) (schemaRow ["IsKey"]))
  270. primaryKey.Add (table.Columns [dsColumnName]);
  271. }
  272. if (MissingSchemaAction == MissingSchemaAction.AddWithKey && primaryKey.Count > 0)
  273. table.PrimaryKey = (DataColumn[])(primaryKey.ToArray());
  274. }
  275. [MonoTODO]
  276. object ICloneable.Clone ()
  277. {
  278. throw new NotImplementedException ();
  279. }
  280. [MonoTODO]
  281. public int Update (DataRow[] dataRows)
  282. {
  283. throw new NotImplementedException (); // FIXME: Which mapping?
  284. }
  285. public override int Update (DataSet dataSet)
  286. {
  287. int result = 0;
  288. foreach (DataTable table in dataSet.Tables)
  289. result += Update (table);
  290. return result;
  291. }
  292. public int Update (DataTable dataTable)
  293. {
  294. int index = TableMappings.IndexOfDataSetTable (dataTable.TableName);
  295. if (index < 0)
  296. throw new ArgumentException ();
  297. return Update (dataTable, TableMappings [index]);
  298. }
  299. private int Update (DataTable dataTable, DataTableMapping tableMapping)
  300. {
  301. DataRow[] rows = new DataRow [dataTable.Rows.Count];
  302. dataTable.Rows.CopyTo (rows, 0);
  303. return Update (rows, tableMapping);
  304. }
  305. [MonoTODO]
  306. protected virtual int Update (DataRow[] dataRows, DataTableMapping tableMapping)
  307. {
  308. int updateCount = 0;
  309. foreach (DataRow row in dataRows) {
  310. StatementType statementType = StatementType.Update;
  311. IDbCommand command = null;
  312. string commandName = String.Empty;
  313. bool useCommandBuilder = false;
  314. switch (row.RowState) {
  315. case DataRowState.Added:
  316. statementType = StatementType.Insert;
  317. command = InsertCommand;
  318. commandName = "Insert";
  319. break;
  320. case DataRowState.Deleted:
  321. statementType = StatementType.Delete;
  322. command = DeleteCommand;
  323. commandName = "Delete";
  324. break;
  325. case DataRowState.Modified:
  326. statementType = StatementType.Update;
  327. command = UpdateCommand;
  328. commandName = "Update";
  329. break;
  330. case DataRowState.Unchanged:
  331. continue;
  332. case DataRowState.Detached:
  333. throw new NotImplementedException ();
  334. }
  335. if (command == null)
  336. useCommandBuilder = true;
  337. RowUpdatingEventArgs args = CreateRowUpdatingEvent (row, command, statementType, tableMapping);
  338. OnRowUpdating (args);
  339. if (args.Status == UpdateStatus.ErrorsOccurred)
  340. throw (args.Errors);
  341. if (command == null && args.Command != null)
  342. command = args.Command;
  343. else if (command == null)
  344. throw new InvalidOperationException (String.Format ("Update requires a valid {0}Command when passed a DataRow collection with modified rows.", commandName));
  345. if (!useCommandBuilder) {
  346. DataColumnMappingCollection columnMappings = tableMapping.ColumnMappings;
  347. foreach (IDataParameter parameter in command.Parameters) {
  348. string dsColumnName = columnMappings [parameter.SourceColumn].DataSetColumn;
  349. DataRowVersion rowVersion = DataRowVersion.Proposed;
  350. // Parameter version is ignored for non-update commands
  351. if (statementType == StatementType.Update)
  352. rowVersion = parameter.SourceVersion;
  353. parameter.Value = row [dsColumnName, rowVersion];
  354. }
  355. row.AcceptChanges ();
  356. }
  357. updateCount += command.ExecuteNonQuery ();
  358. OnRowUpdated (CreateRowUpdatedEvent (row, command, statementType, tableMapping));
  359. }
  360. return updateCount;
  361. }
  362. public int Update (DataSet dataSet, string sourceTable)
  363. {
  364. int result = 0;
  365. DataTableMapping tableMapping = TableMappings [sourceTable];
  366. foreach (DataTable dataTable in dataSet.Tables)
  367. result += Update (dataTable, tableMapping);
  368. return result;
  369. }
  370. protected virtual void OnFillError (FillErrorEventArgs value)
  371. {
  372. if (FillError != null)
  373. FillError (this, value);
  374. }
  375. protected abstract void OnRowUpdated (RowUpdatedEventArgs value);
  376. protected abstract void OnRowUpdating (RowUpdatingEventArgs value);
  377. #endregion // Methods
  378. }
  379. }