SqlCommandBuilder.cs 19 KB

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