SqlCommandBuilder.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  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. using System.Data.ProviderBase;
  37. namespace System.Data.SqlClient {
  38. public sealed class SqlCommandBuilder : AbstractDbCommandBuilder
  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 = (SqlDataReader)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 = (string) schemaRow ["BaseTableName"];
  141. if (tableName != (string) schemaRow["BaseTableName"])
  142. throw new InvalidOperationException ("Dynamic SQL generation is not supported against multiple base tables.");
  143. }
  144. dbSchemaTable = schemaTable;
  145. }
  146. private SqlCommand CreateDeleteCommand (DataRow row, DataTableMapping tableMapping)
  147. {
  148. // If no table was found, then we can't do an delete
  149. if (QuotedTableName == String.Empty)
  150. return null;
  151. CreateNewCommand (ref deleteCommand);
  152. string command = String.Format ("DELETE FROM {0} ", QuotedTableName);
  153. StringBuilder columns = new StringBuilder ();
  154. StringBuilder whereClause = new StringBuilder ();
  155. string dsColumnName = String.Empty;
  156. bool keyFound = false;
  157. int parmIndex = 1;
  158. foreach (DataRow schemaRow in dbSchemaTable.Rows) {
  159. if (!IncludedInWhereClause (schemaRow))
  160. continue;
  161. if (whereClause.Length > 0)
  162. whereClause.Append (" AND ");
  163. bool isKey = (bool) schemaRow ["IsKey"];
  164. SqlParameter parameter = null;
  165. if (!isKey) {
  166. parameter = deleteCommand.Parameters.Add (CreateParameter (parmIndex++, schemaRow));
  167. dsColumnName = tableMapping.ColumnMappings [parameter.SourceColumn].DataSetColumn;
  168. if (row != null)
  169. parameter.Value = row [dsColumnName, DataRowVersion.Current];
  170. whereClause.Append ("(");
  171. whereClause.Append (String.Format (clause1, GetQuotedString (parameter.SourceColumn), parameter.ParameterName));
  172. whereClause.Append (" OR ");
  173. }
  174. else
  175. keyFound = true;
  176. parameter = deleteCommand.Parameters.Add (CreateParameter (parmIndex++, schemaRow));
  177. dsColumnName = tableMapping.ColumnMappings [parameter.SourceColumn].DataSetColumn;
  178. if (row != null)
  179. parameter.Value = row [dsColumnName, DataRowVersion.Current];
  180. whereClause.Append (String.Format (clause2, GetQuotedString (parameter.SourceColumn), parameter.ParameterName));
  181. if (!isKey)
  182. whereClause.Append (")");
  183. }
  184. if (!keyFound)
  185. throw new InvalidOperationException ("Dynamic SQL generation for the DeleteCommand is not supported against a SelectCommand that does not return any key column information.");
  186. // We're all done, so bring it on home
  187. string sql = String.Format ("{0} WHERE ( {1} )", command, whereClause.ToString ());
  188. deleteCommand.CommandText = sql;
  189. return deleteCommand;
  190. }
  191. private SqlCommand CreateInsertCommand (DataRow row, DataTableMapping tableMapping)
  192. {
  193. if (QuotedTableName == String.Empty)
  194. return null;
  195. CreateNewCommand (ref insertCommand);
  196. string command = String.Format ("INSERT INTO {0}", QuotedTableName);
  197. string sql;
  198. StringBuilder columns = new StringBuilder ();
  199. StringBuilder values = new StringBuilder ();
  200. string dsColumnName = String.Empty;
  201. int parmIndex = 1;
  202. foreach (DataRow schemaRow in dbSchemaTable.Rows) {
  203. if (!IncludedInInsert (schemaRow))
  204. continue;
  205. if (parmIndex > 1) {
  206. columns.Append (" , ");
  207. values.Append (" , ");
  208. }
  209. SqlParameter parameter = insertCommand.Parameters.Add (CreateParameter (parmIndex++, schemaRow));
  210. dsColumnName = tableMapping.ColumnMappings [parameter.SourceColumn].DataSetColumn;
  211. if (row != null)
  212. parameter.Value = row [dsColumnName];
  213. columns.Append (GetQuotedString (parameter.SourceColumn));
  214. values.Append (parameter.ParameterName);
  215. }
  216. sql = String.Format ("{0}( {1} ) VALUES ( {2} )", command, columns.ToString (), values.ToString ());
  217. insertCommand.CommandText = sql;
  218. return insertCommand;
  219. }
  220. private void CreateNewCommand (ref SqlCommand command)
  221. {
  222. SqlCommand sourceCommand = SourceCommand;
  223. if (command == null) {
  224. command = sourceCommand.Connection.CreateCommand ();
  225. command.CommandTimeout = sourceCommand.CommandTimeout;
  226. command.Transaction = sourceCommand.Transaction;
  227. }
  228. command.CommandType = CommandType.Text;
  229. command.UpdatedRowSource = UpdateRowSource.None;
  230. }
  231. private SqlCommand CreateUpdateCommand (DataRow row, DataTableMapping tableMapping)
  232. {
  233. // If no table was found, then we can't do an update
  234. if (QuotedTableName == String.Empty)
  235. return null;
  236. CreateNewCommand (ref updateCommand);
  237. string command = String.Format ("UPDATE {0} SET ", QuotedTableName);
  238. StringBuilder columns = new StringBuilder ();
  239. StringBuilder whereClause = new StringBuilder ();
  240. int parmIndex = 1;
  241. string dsColumnName = String.Empty;
  242. bool keyFound = false;
  243. // First, create the X=Y list for UPDATE
  244. foreach (DataRow schemaRow in dbSchemaTable.Rows) {
  245. if (columns.Length > 0)
  246. columns.Append (" , ");
  247. SqlParameter parameter = updateCommand.Parameters.Add (CreateParameter (parmIndex++, schemaRow));
  248. dsColumnName = tableMapping.ColumnMappings [parameter.SourceColumn].DataSetColumn;
  249. if (row != null)
  250. parameter.Value = row [dsColumnName, DataRowVersion.Proposed];
  251. columns.Append (String.Format ("{0} = {1}", GetQuotedString (parameter.SourceColumn), parameter.ParameterName));
  252. }
  253. // Now, create the WHERE clause. This may be optimizable, but it would be ugly to incorporate
  254. // into the loop above. "Premature optimization is the root of all evil." -- Knuth
  255. foreach (DataRow schemaRow in dbSchemaTable.Rows) {
  256. if (!IncludedInWhereClause (schemaRow))
  257. continue;
  258. if (whereClause.Length > 0)
  259. whereClause.Append (" AND ");
  260. bool isKey = (bool) schemaRow ["IsKey"];
  261. SqlParameter parameter = null;
  262. if (!isKey) {
  263. parameter = updateCommand.Parameters.Add (CreateParameter (parmIndex++, schemaRow));
  264. dsColumnName = tableMapping.ColumnMappings [parameter.SourceColumn].DataSetColumn;
  265. if (row != null)
  266. parameter.Value = row [dsColumnName];
  267. whereClause.Append ("(");
  268. whereClause.Append (String.Format (clause1, GetQuotedString (parameter.SourceColumn), parameter.ParameterName));
  269. whereClause.Append (" OR ");
  270. }
  271. else
  272. keyFound = true;
  273. parameter = updateCommand.Parameters.Add (CreateParameter (parmIndex++, schemaRow));
  274. dsColumnName = tableMapping.ColumnMappings [parameter.SourceColumn].DataSetColumn;
  275. if (row != null)
  276. parameter.Value = row [dsColumnName];
  277. whereClause.Append (String.Format (clause2, GetQuotedString (parameter.SourceColumn), parameter.ParameterName));
  278. if (!isKey)
  279. whereClause.Append (")");
  280. }
  281. if (!keyFound)
  282. throw new InvalidOperationException ("Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information.");
  283. // We're all done, so bring it on home
  284. string sql = String.Format ("{0}{1} WHERE ( {2} )", command, columns.ToString (), whereClause.ToString ());
  285. updateCommand.CommandText = sql;
  286. return updateCommand;
  287. }
  288. private SqlParameter CreateParameter (int parmIndex, DataRow schemaRow)
  289. {
  290. string name = String.Format ("@p{0}", parmIndex);
  291. string sourceColumn = (string) schemaRow ["BaseColumnName"];
  292. SqlDbType sqlDbType = (SqlDbType) schemaRow ["ProviderType"];
  293. int size = (int) schemaRow ["ColumnSize"];
  294. return new SqlParameter (name, sqlDbType, size, sourceColumn);
  295. }
  296. public static void DeriveParameters (SqlCommand command)
  297. {
  298. DeriveParameters((AbstractDbCommand)command);
  299. }
  300. protected override void Dispose (bool disposing)
  301. {
  302. if (!disposed) {
  303. if (disposing) {
  304. if (insertCommand != null)
  305. insertCommand.Dispose ();
  306. if (deleteCommand != null)
  307. deleteCommand.Dispose ();
  308. if (updateCommand != null)
  309. updateCommand.Dispose ();
  310. if (dbSchemaTable != null)
  311. dbSchemaTable.Dispose ();
  312. }
  313. disposed = true;
  314. }
  315. }
  316. public SqlCommand GetDeleteCommand ()
  317. {
  318. BuildCache (true);
  319. return CreateDeleteCommand (null, null);
  320. }
  321. public SqlCommand GetInsertCommand ()
  322. {
  323. BuildCache (true);
  324. return CreateInsertCommand (null, null);
  325. }
  326. private string GetQuotedString (string value)
  327. {
  328. if (value == String.Empty || value == null)
  329. return value;
  330. if (quotePrefix == String.Empty && quoteSuffix == String.Empty)
  331. return value;
  332. return String.Format ("{0}{1}{2}", quotePrefix, value, quoteSuffix);
  333. }
  334. public SqlCommand GetUpdateCommand ()
  335. {
  336. BuildCache (true);
  337. return CreateUpdateCommand (null, null);
  338. }
  339. private bool IncludedInInsert (DataRow schemaRow)
  340. {
  341. // If the parameter has one of these properties, then we don't include it in the insert:
  342. // AutoIncrement, Hidden, Expression, RowVersion, ReadOnly
  343. if ((bool) schemaRow ["IsAutoIncrement"])
  344. return false;
  345. if ((bool) schemaRow ["IsHidden"])
  346. return false;
  347. if ((bool) schemaRow ["IsExpression"])
  348. return false;
  349. if ((bool) schemaRow ["IsRowVersion"])
  350. return false;
  351. if ((bool) schemaRow ["IsReadOnly"])
  352. return false;
  353. return true;
  354. }
  355. private bool IncludedInUpdate (DataRow schemaRow)
  356. {
  357. // If the parameter has one of these properties, then we don't include it in the insert:
  358. // AutoIncrement, Hidden, RowVersion
  359. if ((bool) schemaRow ["IsAutoIncrement"])
  360. return false;
  361. if ((bool) schemaRow ["IsHidden"])
  362. return false;
  363. if ((bool) schemaRow ["IsRowVersion"])
  364. return false;
  365. return true;
  366. }
  367. private bool IncludedInWhereClause (DataRow schemaRow)
  368. {
  369. if ((bool) schemaRow ["IsLong"])
  370. return false;
  371. return true;
  372. }
  373. [MonoTODO ("Figure out what else needs to be cleaned up when we refresh.")]
  374. public void RefreshSchema ()
  375. {
  376. tableName = String.Empty;
  377. dbSchemaTable = null;
  378. }
  379. #endregion // Methods
  380. #region Event Handlers
  381. private void RowUpdatingHandler (object sender, SqlRowUpdatingEventArgs e)
  382. {
  383. if (e.Status != UpdateStatus.Continue)
  384. return;
  385. switch (e.StatementType) {
  386. case StatementType.Delete:
  387. deleteCommand = e.Command;
  388. break;
  389. case StatementType.Insert:
  390. insertCommand = e.Command;
  391. break;
  392. case StatementType.Update:
  393. updateCommand = e.Command;
  394. break;
  395. default:
  396. return;
  397. }
  398. try {
  399. BuildCache (false);
  400. switch (e.StatementType) {
  401. case StatementType.Delete:
  402. e.Command = CreateDeleteCommand (e.Row, e.TableMapping);
  403. e.Status = UpdateStatus.Continue;
  404. break;
  405. case StatementType.Insert:
  406. e.Command = CreateInsertCommand (e.Row, e.TableMapping);
  407. e.Status = UpdateStatus.Continue;
  408. break;
  409. case StatementType.Update:
  410. e.Command = CreateUpdateCommand (e.Row, e.TableMapping);
  411. e.Status = UpdateStatus.Continue;
  412. break;
  413. }
  414. if (e.Command != null && e.Row != null) {
  415. e.Row.AcceptChanges ();
  416. e.Status = UpdateStatus.SkipCurrentRow;
  417. }
  418. }
  419. catch (Exception exception) {
  420. e.Errors = exception;
  421. e.Status = UpdateStatus.ErrorsOccurred;
  422. }
  423. }
  424. #endregion // Event Handlers
  425. }
  426. }