SqlCommandBuilder.cs 17 KB

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