SqlCommandBuilder.cs 16 KB

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