SqlCommandBuilder.cs 16 KB

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