SqlCommandBuilder.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. //
  2. // System.Data.SqlClient.SqlCommandBuilder.cs
  3. //
  4. // Author:
  5. // Tim Coleman ([email protected])
  6. //
  7. // Copyright (C) Tim Coleman, 2002
  8. //
  9. using System;
  10. using System.Collections;
  11. using System.ComponentModel;
  12. using System.Data;
  13. using System.Data.Common;
  14. using System.Text;
  15. namespace System.Data.SqlClient {
  16. public sealed class SqlCommandBuilder : Component
  17. {
  18. #region Fields
  19. bool disposed = false;
  20. DataTable dbSchemaTable;
  21. SqlDataAdapter adapter;
  22. string quotePrefix;
  23. string quoteSuffix;
  24. string[] columnNames;
  25. string tableName;
  26. SqlCommand deleteCommand;
  27. SqlCommand insertCommand;
  28. SqlCommand updateCommand;
  29. // Used to construct WHERE clauses
  30. static readonly string clause1 = "({0} IS NULL AND {1} IS NULL)";
  31. static readonly string clause2 = "({0} = {1})";
  32. #endregion // Fields
  33. #region Constructors
  34. public SqlCommandBuilder ()
  35. {
  36. dbSchemaTable = null;
  37. adapter = null;
  38. quoteSuffix = String.Empty;
  39. quotePrefix = String.Empty;
  40. }
  41. public SqlCommandBuilder (SqlDataAdapter adapter)
  42. : this ()
  43. {
  44. DataAdapter = adapter;
  45. }
  46. #endregion // Constructors
  47. #region Properties
  48. [DataSysDescription ("The DataAdapter for which to automatically generate SqlCommands")]
  49. [DefaultValue (null)]
  50. public SqlDataAdapter DataAdapter {
  51. get { return adapter; }
  52. set {
  53. adapter = value;
  54. if (adapter != null)
  55. adapter.RowUpdating += new SqlRowUpdatingEventHandler (RowUpdatingHandler);
  56. }
  57. }
  58. private string QuotedTableName {
  59. get { return GetQuotedString (tableName); }
  60. }
  61. [Browsable (false)]
  62. [DataSysDescription ("The character used in a text command as the opening quote for quoting identifiers that contain special characters.")]
  63. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  64. public string QuotePrefix {
  65. get { return quotePrefix; }
  66. set {
  67. if (dbSchemaTable != null)
  68. throw new InvalidOperationException ("The QuotePrefix and QuoteSuffix properties cannot be changed once an Insert, Update, or Delete command has been generated.");
  69. quotePrefix = value;
  70. }
  71. }
  72. [Browsable (false)]
  73. [DataSysDescription ("The character used in a text command as the closing quote for quoting identifiers that contain special characters.")]
  74. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  75. public string QuoteSuffix {
  76. get { return quoteSuffix; }
  77. set {
  78. if (dbSchemaTable != null)
  79. throw new InvalidOperationException ("The QuotePrefix and QuoteSuffix properties cannot be changed once an Insert, Update, or Delete command has been generated.");
  80. quoteSuffix = value;
  81. }
  82. }
  83. private SqlCommand SourceCommand {
  84. get {
  85. if (adapter != null)
  86. return adapter.SelectCommand;
  87. return null;
  88. }
  89. }
  90. #endregion // Properties
  91. #region Methods
  92. private void BuildCache (bool closeConnection)
  93. {
  94. SqlCommand sourceCommand = SourceCommand;
  95. if (sourceCommand == null)
  96. throw new InvalidOperationException ("The DataAdapter.SelectCommand property needs to be initialized.");
  97. SqlConnection connection = sourceCommand.Connection;
  98. if (connection == null)
  99. throw new InvalidOperationException ("The DataAdapter.SelectCommand.Connection property needs to be initialized.");
  100. if (dbSchemaTable == null) {
  101. if (connection.State == ConnectionState.Open)
  102. closeConnection = false;
  103. else
  104. connection.Open ();
  105. SqlDataReader reader = sourceCommand.ExecuteReader (CommandBehavior.SchemaOnly | CommandBehavior.KeyInfo);
  106. dbSchemaTable = reader.GetSchemaTable ();
  107. reader.Close ();
  108. if (closeConnection)
  109. connection.Close ();
  110. BuildInformation (dbSchemaTable);
  111. }
  112. }
  113. private void BuildInformation (DataTable schemaTable)
  114. {
  115. tableName = String.Empty;
  116. foreach (DataRow schemaRow in schemaTable.Rows) {
  117. if (tableName == String.Empty)
  118. tableName = (string) schemaRow ["BaseTableName"];
  119. if (tableName != (string) schemaRow["BaseTableName"])
  120. throw new InvalidOperationException ("Dynamic SQL generation is not supported against multiple base tables.");
  121. }
  122. dbSchemaTable = schemaTable;
  123. }
  124. private SqlCommand CreateDeleteCommand (DataRow row, DataTableMapping tableMapping)
  125. {
  126. // If no table was found, then we can't do an delete
  127. if (QuotedTableName == String.Empty)
  128. return null;
  129. CreateNewCommand (ref deleteCommand);
  130. string command = String.Format ("DELETE FROM {0} ", QuotedTableName);
  131. StringBuilder columns = new StringBuilder ();
  132. StringBuilder whereClause = new StringBuilder ();
  133. string dsColumnName = String.Empty;
  134. bool keyFound = false;
  135. int parmIndex = 1;
  136. foreach (DataRow schemaRow in dbSchemaTable.Rows) {
  137. if (!IncludedInWhereClause (schemaRow))
  138. continue;
  139. if (whereClause.Length > 0)
  140. whereClause.Append (" AND ");
  141. bool isKey = (bool) schemaRow ["IsKey"];
  142. SqlParameter parameter = null;
  143. if (!isKey) {
  144. parameter = deleteCommand.Parameters.Add (CreateParameter (parmIndex++, schemaRow));
  145. dsColumnName = tableMapping.ColumnMappings [parameter.SourceColumn].DataSetColumn;
  146. if (row != null)
  147. parameter.Value = row [dsColumnName, DataRowVersion.Current];
  148. whereClause.Append ("(");
  149. whereClause.Append (String.Format (clause1, GetQuotedString (parameter.SourceColumn), parameter.ParameterName));
  150. whereClause.Append (" OR ");
  151. }
  152. else
  153. keyFound = true;
  154. parameter = deleteCommand.Parameters.Add (CreateParameter (parmIndex++, schemaRow));
  155. dsColumnName = tableMapping.ColumnMappings [parameter.SourceColumn].DataSetColumn;
  156. if (row != null)
  157. parameter.Value = row [dsColumnName, DataRowVersion.Current];
  158. whereClause.Append (String.Format (clause2, GetQuotedString (parameter.SourceColumn), parameter.ParameterName));
  159. if (!isKey)
  160. whereClause.Append (")");
  161. }
  162. if (!keyFound)
  163. throw new InvalidOperationException ("Dynamic SQL generation for the DeleteCommand is not supported against a SelectCommand that does not return any key column information.");
  164. // We're all done, so bring it on home
  165. string sql = String.Format ("{0} WHERE ( {1} )", command, whereClause.ToString ());
  166. deleteCommand.CommandText = sql;
  167. return deleteCommand;
  168. }
  169. private SqlCommand CreateInsertCommand (DataRow row, DataTableMapping tableMapping)
  170. {
  171. if (QuotedTableName == String.Empty)
  172. return null;
  173. CreateNewCommand (ref insertCommand);
  174. string command = String.Format ("INSERT INTO {0}", QuotedTableName);
  175. string sql;
  176. StringBuilder columns = new StringBuilder ();
  177. StringBuilder values = new StringBuilder ();
  178. string dsColumnName = String.Empty;
  179. int parmIndex = 1;
  180. foreach (DataRow schemaRow in dbSchemaTable.Rows) {
  181. if (!IncludedInInsert (schemaRow))
  182. continue;
  183. if (parmIndex > 1) {
  184. columns.Append (" , ");
  185. values.Append (" , ");
  186. }
  187. SqlParameter parameter = insertCommand.Parameters.Add (CreateParameter (parmIndex++, schemaRow));
  188. dsColumnName = tableMapping.ColumnMappings [parameter.SourceColumn].DataSetColumn;
  189. if (row != null)
  190. parameter.Value = row [dsColumnName];
  191. columns.Append (GetQuotedString (parameter.SourceColumn));
  192. values.Append (parameter.ParameterName);
  193. }
  194. sql = String.Format ("{0}( {1} ) VALUES ( {2} )", command, columns.ToString (), values.ToString ());
  195. insertCommand.CommandText = sql;
  196. return insertCommand;
  197. }
  198. private void CreateNewCommand (ref SqlCommand command)
  199. {
  200. SqlCommand sourceCommand = SourceCommand;
  201. if (command == null) {
  202. command = sourceCommand.Connection.CreateCommand ();
  203. command.CommandTimeout = sourceCommand.CommandTimeout;
  204. command.Transaction = sourceCommand.Transaction;
  205. }
  206. command.CommandType = CommandType.Text;
  207. command.UpdatedRowSource = UpdateRowSource.None;
  208. }
  209. private SqlCommand CreateUpdateCommand (DataRow row, DataTableMapping tableMapping)
  210. {
  211. // If no table was found, then we can't do an update
  212. if (QuotedTableName == String.Empty)
  213. return null;
  214. CreateNewCommand (ref updateCommand);
  215. string command = String.Format ("UPDATE {0} SET ", QuotedTableName);
  216. StringBuilder columns = new StringBuilder ();
  217. StringBuilder whereClause = new StringBuilder ();
  218. int parmIndex = 1;
  219. string dsColumnName = String.Empty;
  220. bool keyFound = false;
  221. // First, create the X=Y list for UPDATE
  222. foreach (DataRow schemaRow in dbSchemaTable.Rows) {
  223. if (columns.Length > 0)
  224. columns.Append (" , ");
  225. SqlParameter parameter = updateCommand.Parameters.Add (CreateParameter (parmIndex++, schemaRow));
  226. dsColumnName = tableMapping.ColumnMappings [parameter.SourceColumn].DataSetColumn;
  227. if (row != null)
  228. parameter.Value = row [dsColumnName, DataRowVersion.Proposed];
  229. columns.Append (String.Format ("{0} = {1}", GetQuotedString (parameter.SourceColumn), parameter.ParameterName));
  230. }
  231. // Now, create the WHERE clause. This may be optimizable, but it would be ugly to incorporate
  232. // into the loop above. "Premature optimization is the root of all evil." -- Knuth
  233. foreach (DataRow schemaRow in dbSchemaTable.Rows) {
  234. if (!IncludedInWhereClause (schemaRow))
  235. continue;
  236. if (whereClause.Length > 0)
  237. whereClause.Append (" AND ");
  238. bool isKey = (bool) schemaRow ["IsKey"];
  239. SqlParameter parameter = null;
  240. if (!isKey) {
  241. parameter = updateCommand.Parameters.Add (CreateParameter (parmIndex++, schemaRow));
  242. dsColumnName = tableMapping.ColumnMappings [parameter.SourceColumn].DataSetColumn;
  243. if (row != null)
  244. parameter.Value = row [dsColumnName];
  245. whereClause.Append ("(");
  246. whereClause.Append (String.Format (clause1, GetQuotedString (parameter.SourceColumn), parameter.ParameterName));
  247. whereClause.Append (" OR ");
  248. }
  249. else
  250. keyFound = true;
  251. parameter = updateCommand.Parameters.Add (CreateParameter (parmIndex++, schemaRow));
  252. dsColumnName = tableMapping.ColumnMappings [parameter.SourceColumn].DataSetColumn;
  253. if (row != null)
  254. parameter.Value = row [dsColumnName];
  255. whereClause.Append (String.Format (clause2, GetQuotedString (parameter.SourceColumn), parameter.ParameterName));
  256. if (!isKey)
  257. whereClause.Append (")");
  258. }
  259. if (!keyFound)
  260. throw new InvalidOperationException ("Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information.");
  261. // We're all done, so bring it on home
  262. string sql = String.Format ("{0}{1} WHERE ( {2} )", command, columns.ToString (), whereClause.ToString ());
  263. updateCommand.CommandText = sql;
  264. return updateCommand;
  265. }
  266. private SqlParameter CreateParameter (int parmIndex, DataRow schemaRow)
  267. {
  268. string name = String.Format ("@p{0}", parmIndex);
  269. string sourceColumn = (string) schemaRow ["BaseColumnName"];
  270. SqlDbType sqlDbType = (SqlDbType) schemaRow ["ProviderType"];
  271. int size = (int) schemaRow ["ColumnSize"];
  272. return new SqlParameter (name, sqlDbType, size, sourceColumn);
  273. }
  274. public static void DeriveParameters (SqlCommand command)
  275. {
  276. command.DeriveParameters ();
  277. }
  278. protected override void Dispose (bool disposing)
  279. {
  280. if (!disposed) {
  281. if (disposing) {
  282. if (insertCommand != null)
  283. insertCommand.Dispose ();
  284. if (deleteCommand != null)
  285. deleteCommand.Dispose ();
  286. if (updateCommand != null)
  287. updateCommand.Dispose ();
  288. if (dbSchemaTable != null)
  289. dbSchemaTable.Dispose ();
  290. }
  291. disposed = true;
  292. }
  293. }
  294. public SqlCommand GetDeleteCommand ()
  295. {
  296. BuildCache (true);
  297. return CreateDeleteCommand (null, null);
  298. }
  299. public SqlCommand GetInsertCommand ()
  300. {
  301. BuildCache (true);
  302. return CreateInsertCommand (null, null);
  303. }
  304. private string GetQuotedString (string value)
  305. {
  306. if (value == String.Empty || value == null)
  307. return value;
  308. if (quotePrefix == String.Empty && quoteSuffix == String.Empty)
  309. return value;
  310. return String.Format ("{0}{1}{2}", quotePrefix, value, quoteSuffix);
  311. }
  312. public SqlCommand GetUpdateCommand ()
  313. {
  314. BuildCache (true);
  315. return CreateUpdateCommand (null, null);
  316. }
  317. private bool IncludedInInsert (DataRow schemaRow)
  318. {
  319. // If the parameter has one of these properties, then we don't include it in the insert:
  320. // AutoIncrement, Hidden, Expression, RowVersion, ReadOnly
  321. if ((bool) schemaRow ["IsAutoIncrement"])
  322. return false;
  323. if ((bool) schemaRow ["IsHidden"])
  324. return false;
  325. if ((bool) schemaRow ["IsExpression"])
  326. return false;
  327. if ((bool) schemaRow ["IsRowVersion"])
  328. return false;
  329. if ((bool) schemaRow ["IsReadOnly"])
  330. return false;
  331. return true;
  332. }
  333. private bool IncludedInUpdate (DataRow schemaRow)
  334. {
  335. // If the parameter has one of these properties, then we don't include it in the insert:
  336. // AutoIncrement, Hidden, RowVersion
  337. if ((bool) schemaRow ["IsAutoIncrement"])
  338. return false;
  339. if ((bool) schemaRow ["IsHidden"])
  340. return false;
  341. if ((bool) schemaRow ["IsRowVersion"])
  342. return false;
  343. return true;
  344. }
  345. private bool IncludedInWhereClause (DataRow schemaRow)
  346. {
  347. if ((bool) schemaRow ["IsLong"])
  348. return false;
  349. return true;
  350. }
  351. [MonoTODO ("Figure out what else needs to be cleaned up when we refresh.")]
  352. public void RefreshSchema ()
  353. {
  354. tableName = String.Empty;
  355. dbSchemaTable = null;
  356. }
  357. #endregion // Methods
  358. #region Event Handlers
  359. private void RowUpdatingHandler (object sender, SqlRowUpdatingEventArgs e)
  360. {
  361. if (e.Status != UpdateStatus.Continue)
  362. return;
  363. switch (e.StatementType) {
  364. case StatementType.Delete:
  365. deleteCommand = e.Command;
  366. break;
  367. case StatementType.Insert:
  368. insertCommand = e.Command;
  369. break;
  370. case StatementType.Update:
  371. updateCommand = e.Command;
  372. break;
  373. default:
  374. return;
  375. }
  376. try {
  377. BuildCache (false);
  378. switch (e.StatementType) {
  379. case StatementType.Delete:
  380. e.Command = CreateDeleteCommand (e.Row, e.TableMapping);
  381. e.Status = UpdateStatus.Continue;
  382. break;
  383. case StatementType.Insert:
  384. e.Command = CreateInsertCommand (e.Row, e.TableMapping);
  385. e.Status = UpdateStatus.Continue;
  386. break;
  387. case StatementType.Update:
  388. e.Command = CreateUpdateCommand (e.Row, e.TableMapping);
  389. e.Status = UpdateStatus.Continue;
  390. break;
  391. }
  392. if (e.Command != null && e.Row != null) {
  393. e.Row.AcceptChanges ();
  394. e.Status = UpdateStatus.SkipCurrentRow;
  395. }
  396. }
  397. catch (Exception exception) {
  398. e.Errors = exception;
  399. e.Status = UpdateStatus.ErrorsOccurred;
  400. }
  401. }
  402. #endregion // Event Handlers
  403. }
  404. }