SqlCommandBuilder.cs 18 KB

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